2016-09-26 24 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

是的。這可以做到。 –

相關問題