Creating and executable JAR file that uses an exte

2019-06-07 14:41发布

问题:

I have a java application in Eclipse that uses an eml file like so

File matches = new File("matches.xml");

The file is located in the default package as all the other classes. When I create the JAR it bundles in the XML file with it. My application require me to be able to make changes to the XML file. How can I set it up so the JAR can reference the XML file outside of itself?

回答1:

My application require me to be able to make changes to the XML file.

Then you will need to extract it from the Jar and save it somewhere on the local file system.

See How can an app use files inside the JAR for read and write? for more details.



回答2:

If you're using new File("matches.xml") that won't use a file within a jar file at all. It will only look on the external file system.

If you need to be able to use an external file if it's present, or the version in the jar file as a fallback, you'll need to test for the file's existence (File.exists()) and use Class.getResourceAsStream("matches.xml") for the fallback behaviour.



回答3:

As you want to keep the file outside the jar and want to update it so the jar can read, so you can put the file in the same directory where the jar is and use the following code to access the file

FileInputStream file = new java.io.FileInputStream("matches.xml"); 

So this can be the directory structure.

- matches\
    - matches.jar
    - matches.xml