views:

19

answers:

1

In my Netbeans Maven project, I have the following code in the main method:

FileInputStream in = new FileInputStream("database.properties");

but always get a file not found error.

I have put the file in src/main/resources and it is properly copied to the target/classes directory (I believe that is the expected behavior for Maven resources) but when actually running the program (via shift-f6) it seems it can never find the file. I've tried various other paths:

FileInputStream in = new FileInputStream("./database.properties");
FileInputStream in = new FileInputStream("resources/database.properties");

etc. but nothing seems to work.

So what is the proper path to use?


Based on "disown's" answer below, here was what I needed:

InputStream in = TestDB.class.getResourceAsStream("/database.properties")

where TestDB is the name of the class.

Thanks for your help, disown!

+2  A: 

You cannot load the file directly like that, you need to use the resource abstraction (a resource could not only be in the file system, but on any place on the classpath - in a jar file or otherwise). This abstraction is what you need to use when loading resources. Resource paths are relative to the location of your class file, so you need to prepend a slash to get to the 'root':

InputStream in = getClass().getResourceAsStream("/database.properties");
disown
If you're trying to access the file from a static method, getClass() doesn't work. Is there an alternative in that case?
Aaron L. Carlow
Use the class name, for instance Main.class.getResourceAsStream(). You can use any class or class loader, so hread.getContextClassLoader().getResourceAsStream() also works.
disown