做了个小项目练练手,出了个问题(以前没这么搞过)。
工程目录是这样的:src源文件夹中有ui, model, data, config, images文件夹。ui文件夹是main方法所在文件夹;config文件夹中有一个config.xml文件,程序运行时,会从这个配置文件中读取配置信息,同时程序中有一个设置修改按键,可以对这个文件进行配置修改。在MyEclipse中可以正确的修改,但打成可运行的jar包后,配置信息可以正确读取,可是不能修改了。
我自己认为可能是打成Jar包后文件的路径出问题了。哪位帮解决下,谢谢了。(XML解析用的是dom4j开源包)
部分代码如下:
配置读取的代码:
configVisitor是读取配置的Visitor。
static {
SAXReader saxr = new SAXReader();
InputStream is = Manager.class.getClassLoader().getResourceAsStream("config/config.xml");
try {
Document doc = saxr.read(is);
doc.accept(new configVisitor());
} catch (DocumentException e) {
e.printStackTrace();

}
修改配置的代码:
其中Manager是main所在类。ModifyVisitor是修改配置的Visitor。
public static void modify(String title, Setting setting) {
SAXReader saxr = new SAXReader();
InputStream is = EVELossManager.class.getClassLoader().getResourceAsStream("config/config.xml");

try {
Document doc = saxr.read(is);
doc.accept(new ModifyVisitor(title, setting));
String path = Manager.class.getClassLoader().getResource("config/config.xml").toString();
File f = new File(path.replaceAll("file:/", ""));
FileOutputStream newFile = new FileOutputStream(f);
            XMLWriter newWriter = new XMLWriter(newFile);
            newWriter.write(doc);
            newWriter.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();

}

解决方案 »

  1.   

    简单的说问题就是 
    把工程打成可运行JAR包后,能够正常读取JAR包中的config.xml文件,但对其进行修改时没有任何变化。
    不打成JAR包时,可以正常的读取和修改。
      

  2.   

    问题发现了,
    原来是有报异常,我没有打开本地后台。
    打成JAR包后,上面代码中的Path打印出来是这样的路径rsrc:config/config.xml 于是建立FileOutputStream时抛异常了:FileNotFoundException: rsrc:config\config.xml (文件名、目录名或卷标语法不正确。)
    没打成JAR包时,path路径是完整的URI路径。
    问题又来了,怎么在JAR包中 生成那个config.xml文件呢(打成的JAR包随时会改变其在电脑上的位置的) 晕了