我的类路径中有一个文件,例如com/path/to/file.txt。我需要将此文件作为java.io.File对象加载或引用。这是因为我需要使用访问文件java.io.RandomAccessFile(文件很大,并且我需要查找某个字节偏移量)。这可能吗?的构造函数RandomAccessFile需要File实例或字符串(路径)。
如果还有另一种方法寻求某个字节偏移并读取该行,我也很乐意。
Answers:
尝试获取您的类路径资源的URL:
URL url = this.getClass().getResource("/com/path/to/file.txt")
然后使用接受URI的构造函数创建一个文件:
File file = new File(url.toURI());
    这也可以,并且不需要/ path / to / file URI转换。如果文件在类路径中,则将找到它。
File currFile = new File(getClass().getClassLoader().getResource("the_file.txt").getFile());
    File构造函数
                    我发现此单行代码最有效,最有用:
File file = new File(ClassLoader.getSystemResource("com/path/to/file.txt").getFile());
奇迹般有效。
File file = new File(ClassLoader.getSystemResource("com/path/to/file.txt").toURI());
                    或使用InputStream绝对CLASSPATH路径(以/斜杠字符开头)直接使用资源的:
getClass().getResourceAsStream("/com/path/to/file.txt");
或相对的CLASSPATH路径(当您编写的类与资源文件本身位于同一Java包中时,即com.path.to):
getClass().getResourceAsStream("file.txt");
    java.io.InputStream.skip(long)方法跳过文件中的某个偏移量,然后例如通过使用该java.io.BufferedReader.readLine()方法读取一行。这个问题还针对其他解决方案,而不仅仅是RandomAccessFile一个。