简体   繁体   English

写入jar内的文件

[英]Writing to a file inside of a jar

I am having a problem writing to a .xml file inside of my jar. 我在将jar写入.xml文件时遇到问题。 When I use the following code inside of my Netbeans IDE, no error occurs and it writes to the file just fine. 当我在Netbeans IDE中使用以下代码时,不会发生任何错误,并且可以将其写入文件。

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: 但是,当我执行jar时,出现错误消息:

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. 有谁知道为什么我在Netbeans中运行它为什么可以运行,但是当我执行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 当您使用.toURI()时,它会返回类似

D:/folderName/folderName/Settings.xml

and hence you get the exception "URI is not hierarchical" 因此,您将获得异常“ URI不是分层的”

To avoid this call the method getPath() on the URI returned, which returns something like 为了避免此调用,返回的URI上的方法getPath()会返回类似

/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. 如果可以找到合适的位置,可以将Settings.xml放在文件系统中。 This is most likely vendor and platform specific, but can be done. 这很可能是特定于供应商和平台的,但是可以完成。

Settings.xml的位置添加到classpath

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM