znat
znat

Reputation: 13474

How to open and read a file in the src/my/package folder?

I would like to load the contents of a text file in a String. The text file should stay in the same folder src/my/package as the .java.

However, I can't find the path to this file: I have tried:

File f = new File("src/my/package/file.js"); 
File f = new File("file.js"); 

and many others but nothing worked.

What is the correct path to my file?

Upvotes: 0

Views: 3110

Answers (1)

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

To open files located on the classpath, use the Class.getResource() family of methods. They work even if the file is inside a jar file with your classes. So something like

InputStream is = getClass().getResourceAsStream("/my/package/file.js");

Upvotes: 5

Related Questions