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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4359876/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:28:17  来源:igfitidea点击:

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

javaclasspath

提问by jake

I have a file that is in my classpath, e.g. com/path/to/file.txt. I need to load or reference this file as a java.io.Fileobject. The is because I need to access the file using java.io.RandomAccessFile(the file is large, and I need to seek to a certain byte offset). Is this possible? The constructors for RandomAccessFilerequire a Fileinstance or String (path).

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

If there's another solution to seek to a certain byte offset and read the line, I'm open to that as well.

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

回答by joelittlejohn

Try getting hold of a URL for your classpath resource:

尝试获取类路径资源的 URL:

URL url = this.getClass().getResource("/com/path/to/file.txt")

Then create a file using the constructor that accepts a URI:

然后使用接受 URI 的构造函数创建一个文件:

File file = new File(url.toURI());

回答by Jiri Patera

Or use directly the InputStreamof the resource using the absolute CLASSPATH path (starting with the /slash character):

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


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

Or relative CLASSPATH path (when the class you are writing is in the same Java package as the resource file itself, i.e. com.path.to):

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


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

回答by Hotel

This also works, and doesn't require a /path/to/file URI conversion. If the file is on the classpath, this will find it.

这也有效,并且不需要 /path/to/file URI 转换。如果文件在类路径上,这将找到它。

File currFile = new File(getClass().getClassLoader().getResource("the_file.txt").getFile());

回答by Gondy

I find this one-line code as most efficient and useful:

我发现这个单行代码最有效和有用:

File file = new File(ClassLoader.getSystemResource("com/path/to/file.txt").getFile());

Works like a charm.

奇迹般有效。