psylocybe
psylocybe

Reputation: 23

How to retrieve .properties?

Im developing desktop java application using maven. I got a *.properties file that I need to retrive during execution (src/resources/application.properties). The only thing comes to my mind is to use:

private Properties applicationProperties;
applicationProperties.load(new BufferedInputStream(new FileInputStream("src/resources/application.properties")));

This would work if I run my application directly from IDE. I want to to keep outpout hierarchy clear, so I set maven to copy resources folder dircetly to target folder (which is a basedir for the output application). This way application.properties file won't load (since I have target/resources/application.properties but not target/src/resources/application.properties).

What is the best way to manage resources so they work both when I debug from IDE and run builded jar file directly?

Upvotes: 0

Views: 232

Answers (2)

Chris
Chris

Reputation: 23171

You should load the property file from the classpath rather than from an explicit file system location:

 applicationProperties.load(new BufferedInputStream(this.getClass().getResourceAsStream( "/application.properties" );

As long as your IDE is configured to include the resources directory on your classpath (this should be the default with Maven), then this will work whether you're running within the IDE or not since maven will copy the resources to the right place when packaging your archive.

Upvotes: 1

Bozho
Bozho

Reputation: 597046

Don't expect files to be in the src folder - it doesn't exist at runtime. The properties files go to /bin. But don't rely on that either. Because FileInputStream takes absolute paths only.

When you need a classpath-relative path, use:

InputStream is = YourClass.class.getResourceAsStream("/a.properties")`

(maven sends files from /src/main/resources to the root of the classpath)

Upvotes: 1

Related Questions