繁体   English   中英

如何从类路径加载/引用文件作为 File 实例

[英]How to load/reference a file as a File instance from the classpath

我的类路径中有一个文件,例如com/path/to/file.txt 我需要将此文件作为java.io.File对象加载或引用。 这是因为我需要使用java.io.RandomAccessFile访问文件(文件很大,我需要寻找某个字节偏移量)。 这可能吗? RandomAccessFile的构造函数需要一个File实例或 String(路径)。

如果有另一种解决方案来寻找某个字节偏移量并读取该行,我也对此持开放态度。

尝试获取类路径资源的 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 = new File(ClassLoader.getSystemResource("com/path/to/file.txt").getFile());

奇迹般有效。

或者直接使用资源的InputStream使用绝对 CLASSPATH 路径(以/斜线字符开头):


getClass().getResourceAsStream("/com/path/to/file.txt");

或相对 CLASSPATH 路径(当您编写的类与资源文件本身在同一个 Java 包中时,即com.path.to ):


getClass().getResourceAsStream("file.txt");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM