2016-09-26 27 views
1

我的Java程序中有一个属性文件,它存储了多个值。在设置窗口中,用户可以编辑这些值并在下次运行程序时保存修改。属性文件中的更改没有保存在JAR文件中

下面是加载属性形成属性文件中的代码:

public class AppProperties { 
    private final static AppProperties appProperties = new AppProperties(); 
    private static Properties properties; 
    private final static String preferencesSourcePath = "/res/pref/Properties.properties"; 

    private AppProperties() { 
     properties = new Properties(); 

     try { 
      properties.load(getClass().getResourceAsStream(preferencesSourcePath)); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

在这里,即保存在属性文件中的属性(在相同的类)的方法:

public static void saveAppPropertiesFile() { 
     try { 
      OutputStream outputStream = new FileOutputStream(new File(AppProperties.class.getResource(preferencesSourcePath).getPath())); 
      properties.store(outputStream, null); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

我已经尝试过这个功能,当我在我的IDE中时,它做的很好,但是当我运行JAR文件时它不起作用。实际上,它适用于当前会话,但不会保存在JAR文件中。

在控制台,它说:

java.io.FileNotFoundException: file:\C:\Users\HP\HEIG\EcoSimSOO\out\artifacts\EcoSimSOO_jar\EcoSimSOO.jar!\res\pref\Properties.properties (La syntaxe du nom de fichier, de répertoire ou de volume est incorrecte) 
    at ... 
    at res.pref.AppProperties.saveAppPropertiesFile(AppProperties.java:31) 

这也正是我尝试这样做:

AppProperties.class.getResource(preferencesSourcePath) 

我已阅读this post但我不明白的问题,我有什么要解决这个问题...

谢谢你的帮助。

+0

jar在IDE中使用相对路径时使用绝对路径多数民众赞成为什么你无法找到路径 – SarthAk

+0

尝试打印路径新文件(AppProperties.class.getResource(preferencesSourcePath).getPath()) – SarthAk

+0

也添加你从哪里正在运行罐子 – SarthAk

回答

2

您不应该将任何内容写入JAR文件。从技术上讲,JAR下的资源是只读的。您无法编写/修改JAR内的任何文件。

我在我的Java程序中有一个属性文件,它存储了几个值。在设置窗口中,用户可以编辑这些值并在下次运行程序时保存修改。

而是节省的属性,这些修改后的值的文件,你可以使用一个数据库/缓存/平面文件来存储这些值,并在运行时读取它们。

+0

好的。所以如果我想保存属性文件中的修改,我必须将属性文件存储在JAR文件之外? –

+0

是的。这可以做到。 –

相关问题