简体   繁体   中英

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?

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM