简体   繁体   中英

Writing to a file inside of a jar

I am having a problem writing to a .xml file inside of my jar. When I use the following code inside of my Netbeans IDE, no error occurs and it writes to the file just fine.

public void saveSettings(){
    Properties prop = new Properties();
    FileOutputStream out;
    try {
        File file = new File(Duct.class.getResource("/Settings.xml").toURI());
        out = new FileOutputStream(file);
        prop.setProperty("LAST_FILE", getLastFile());
        try {
            prop.storeToXML(out,null);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.toString());
        }
        try {
            out.close();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.toString());
        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e.toString());
    }
}

However, when I execute the jar I get an error saying:

IllegalArguementException: uri is not hierachal

Does anyone have an idea of why it's working when i run it in Netbeans, but not working when i execute the jar. Also does anyone have a solution to the problem?

I was also struggling with this exception. But finally found out the solution.

When you use .toURI() it returns some thing like

D:/folderName/folderName/Settings.xml

and hence you get the exception "URI is not hierarchical"

To avoid this call the method getPath() on the URI returned, which returns something like

/D:/folderName/folderName/Settings.xml

which is now hierarchical.

In your case, the 5th line in your code should be

File file = new File(Duct.class.getResource("/Settings.xml").toURI().getPath());

The default class loader expects the classpath to be static (so it can cache heavily), so this approach will not work.

You can put Settings.xml in the file system if you can get a suitable location to put it. This is most likely vendor and platform specific, but can be done.

Settings.xml的位置添加到classpath

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