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

JavaClasspath

Java Problem Overview


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.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.

Java Solutions


Solution 1 - Java

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());

Solution 2 - Java

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());

Solution 3 - Java

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.

Solution 4 - Java

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");


Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjakeView Question on Stackoverflow
Solution 1 - JavajoelittlejohnView Answer on Stackoverflow
Solution 2 - JavaHotelView Answer on Stackoverflow
Solution 3 - JavaGondyView Answer on Stackoverflow
Solution 4 - JavaJiri PateraView Answer on Stackoverflow