简体   繁体   中英

Java properties file path

I am reading properties file by a path like this:

String filePath = "src/main/resources/database.properties";

After I build the jar, the jar tries to again find properties file at this particular path, but fails. Is there a way to pack properties files inside the jar or have a neutral path (path which applies both ways with or without building jar) or any other solution to this?

Files in "src/main/resources" automatically get bundled into the jar file, meaning that they can be used at runtime no matter where they are run.

If you want to access files inside the JAR, you can use methods provided by Java:

// Get the resource "test.properties" inside the current package.
getClass().getResource("test.properties");
// Get the resource "test.properties" inside "src/main/resources". 
getClass().getResource("/test.properties");

If you want an input stream, you can use getResourceAsStream :

InputStream propertiesInput = getClass().getResourceAsStream("/test.properties");

You can combine this with a Properties object to read the resource as a properties file:

InputStream propertiesInput = getClass().getResourceAsStream("/test.properties");

Properties testProperties = new Properties();
testProperties.load(propertiesInput);

propertiesInput.close();

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