简体   繁体   中英

Read a file in Java in the same folder of the runtime jar

I have a Maven Java application which accesses an XML configuration file. This configuration file should be placed in the same folder of the application jar so that any configuration would easily "follow" the application.

I use the following piece of code to get the jar's absolute path

String path = Runner.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");

Running it in debug mode returns the following path

/C:/Users/user/git/project/project/target/classes/

So the jar is run (in debug mode) from the target/classes folder thus the XML config file should be placed in that folder.

The problem is that whenever I rebuild the project the target folder gets overwritten and the config file deleted.

Is there any way to solve this problem, which affects only the development phase? I was thinking about telling Maven to not delete the config file in some way, but I don't know how.

Thank you in advance

Best regards,

Giulio

This can be achived using maven out of the box. Simply put the XML file in src/main/resources/, during the build it will be copied into target/classes

mvn archetype:create -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=sub.optimal.example -DartifactId=superapp
cd superapp/
mkdir src/main/resources
touch src/main/resources/example.xml
mvn package
ls target/classes/*.xml

cheers

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