2012-11-10 97 views
1

我目前加載屬性文件是這樣的:如何從根目錄加載屬性文件?

private Properties loadProperties(String filename) throws IOException{ 
     InputStream in = ClassLoader.getSystemResourceAsStream(filename); 
     if (in == null) { 
      throw new FileNotFoundException(filename + " file not found"); 
     } 
     Properties props = new Properties(); 
     props.load(in); 
     in.close(); 
     return props; 
    } 

然而,此刻我的文件規定在SCR \ user.properties路徑。

但是,當我想寫一個屬性文件:

properties.setProperty(username, decryptMD5(password)); 
     try { 
      properties.store(new FileOutputStream("user.properties"), null); 
      System.out.println("Wrote to propteries file!" + username + " " + password); 

這段代碼生成我在我的項目的根文件夾級別的新文件。

但我想有一個文件中寫入\讀取。

因此,如何做到這一點?

PS:當我想指定的路徑我得到「不允許修改文件...」

+0

也許東西線嘗試更改權限? –

回答

2

,因爲你要創建的時候你是一個新的文件創建一個新文件的原因寫作。您應該先處理要作爲File對象寫入的user.properties,然後嘗試寫入它。

的代碼看起來沿

properties.setProperty(username, decryptMD5(password)); 
try{ 
    //get the filename from url class 
    URL url = ClassLoader.getSystemResource("user.properties"); 
    String fileName = url.getFile(); 

    //write to the file 
    props.store(new FileWriter(fileName),null); 
    properties.store(); 
}catch(Exception e){ 
    e.printStacktrace(); 
} 
+0

thx您的評論!但是你描述的我已經在做...;(它不起作用...) – maximus

+0

在你的情況下,新的FileOutputStream創建一個新的文件,在提供的解決方案中,首先從系統資源獲取fileName,然後寫入它使用文件編寫器對同一個文件執行 您爲讀取和寫入生成的文件對象應該與系統資源相同 讓我知道它是否不起作用。 –