开发者

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

开发者 https://www.devze.com 2023-01-29 03:17 出处:网络
I have a file that is in my classpath, e.g. com/path/to/file.txt. I need to load or reference t开发者_开发知识库his file as a java.io.File object. The is because I need to access the file using java.i

I have a file that is in my classpath, e.g. com/path/to/file.txt. I need to load or reference t开发者_开发知识库his file as a java.io.File object. 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 RandomAccessFile require a File instance or String (path).

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


Try getting hold of a URL for your classpath resource:

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

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

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


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

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


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.


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


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):


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

0

精彩评论

暂无评论...
验证码 换一张
取 消