Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

classpath

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.

like image 505
jake Avatar asked Dec 05 '10 16:12

jake


People also ask

How do I load a file from classpath?

We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them. So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.

Where is the classpath in spring boot?

In the Spring Boot's docs here, about serving static content, it says: By default Spring Boot will serve static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath. and all will work fine and I'm happy since I can have my static content under the src directory.


2 Answers

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()); 
like image 179
joelittlejohn Avatar answered Sep 22 '22 12:09

joelittlejohn


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()); 
like image 42
Hotel Avatar answered Sep 24 '22 12:09

Hotel