简体   繁体   中英

.Xml file is not packaged when I build jar

This is the structure of my project in IntellijIDEA

Structure

When I build my jar file it doesn't package the characters.xml file.

Document doc = builder.parse("characters.xml");

This is how I source it in the code. There is obviously a mistake here but I can't figure out where to put it and what path I should write.

The documentation for DocumentBuilder.parse(String) states:

Parse the content of the given URI as an XML document and return a new DOM Document object.

"characters.xml" is technically a valid URI, but it is a relative URI, and there is no base URI against which to resolve it.

To read a file inside a .jar, you use Class.getResource or Class.getResourceAsStream . An example would be:

Document doc;
try (InputStream stream = Controller.class.getResourceAsStream("characters.xml")) {
    doc = builder.parse(stream);
}

Alternatively, you could convert the resource to a URI:

Document doc = builder.parse(
    Controller.class.getResource("characters.xml").toString());

Note that both Class.getResource and Class.getResourceAsStream return null if the argument is not a path of an existing jar entry. You will need to move characters.xml into your src\\sample directory. You may want to verify that the .jar file contains characters.xml by examining it in your IDE's “Files” area.

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