Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the path to resource files in a Maven project?

Tags:

java

maven-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!

like image 759
acarlow Avatar asked Jun 23 '10 18:06

acarlow


People also ask

Where is resources folder in Maven project?

By default, Maven will look for your project's resources under src/main/resources .

Where do Maven project files go?

In a project that follows the mavenSW conventions, resources such as *. properties files can be placed in a src/main/resources directory. The files/folders in this directory will be copied to the root level of the jarW (or other similar package) that is generated for the project.

Where do you put resources in POM?

Via the resources area in the pom you can filter files from their way src/main/resources to the target/classes folder. The lifecycle of Maven is not influenced by this. I have added resources successfully in . Jar file.

How do I give path to src main resources?

The simplest approach uses an instance of the java. io. File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file.


1 Answers

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"); 
like image 67
Alexander Torstling Avatar answered Oct 05 '22 15:10

Alexander Torstling