Java – the path to resource files in a Maven project

javamaven-2

In my 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 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!

Best Answer

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