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

jake picture jake · Dec 5, 2010 · Viewed 111.6k times · Source

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.

Answer

joelittlejohn picture joelittlejohn · Dec 5, 2010

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