How to upload / link to a file as an instance of a file from the classpath

I have a file that is in my classpath. For example, com / path / to / file.txt. I need to download or reference this file as a java.io.File object. The reason is because I need to access the file using java.io.RandomAccessFile (the file is large and I need to look for the byte offset). Is it possible? RandomAccessFile constructors require an instance of File or String (path).

If there is another way to find a specific byte offset and read a string, I also open this solution.

thank.

+51
java
Dec 05 '10 at 16:42
source share
4 answers

Try to get the url of your pathpath resource:

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

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

 File file = new File(url.toURI()); 
+171
Dec 05 '10 at 16:57
source share

This also works and does not require a URI / path / to / file conversion. If the file is in the classpath, it will find it.

 File currFile = new File(getClass().getClassLoader().getResource("the_file.txt").getFile()); 
+41
Jan 08 '14 at 23:16
source share

I find this one line code the most efficient and useful:

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

It works like a charm.

+14
Jul 16 '15 at 14:10
source share

Or use the Resource's InputStream directly, using the absolute CLASSPATH path (starting with a slash / ):

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

Or the 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");
getClass().getResourceAsStream("file.txt"); 
+3
Dec 05 '10 at 17:03
source share



All Articles