2012-11-10 91 views
5

我想寫入* .properties文件。多數民衆贊成我的代碼如何做到這一點:寫入屬性文件不起作用

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

我沒有得到一個例外,但我也沒有得到輸出寫入文件。

這裏也是我的文件結構:

enter image description here

我很欣賞你的答案!

UPDATE

我打開我的屬性與文件:

InputStream in = ClassLoader.getSystemResourceAsStream(filename); 

我的問題是,如何將它從一個特定的路徑加載?

這裏是我的「新」的文件結構:

enter image description here

+1

我測試了你的代碼,我的屬性文件創建在我的工作目錄中。當然,你的文件結構是錯誤的。我猜你必須使用文件路徑而不是僅使用文件名 – ElderMael

+0

當我使用\\ user.properties這樣的路徑時我得到「您無權訪問該文件...」 – maximus

回答

3

這裏是我的測試代碼:

@Test 
public void fileTest() throws FileNotFoundException, IOException { 

    File file = null; 

    Properties props = new Properties(); 

    props.setProperty("Hello", "World"); 

    URL url = Thread.currentThread().getContextClassLoader() 
      .getResource("exceptions/user.properties"); 

    try { 
     file = new File(url.toURI().getPath()); 

     assertTrue(file.exists()); 
    } catch (URISyntaxException e) { 

     e.printStackTrace(); 
    } 

    props.store(new FileOutputStream(file), "OMG, It werks!"); 

} 

它創建並重寫一個文件在我的目標/班/異常目錄(在maven/eclipse中),所以我想它確實有效,但是當然這並不是在JAR文件中測試的。

以下是文件:

#OMG, It werks! 
#Sat Nov 10 08:32:44 CST 2012 
Hello=World 

此外,檢查了這個問題:How can i save a file to the class path

因此,也許你想要做的永遠不會工作的。

+0

我是printint他URL檢查和它給我的 :/ C:/Users/IBM_ADMIN/workspace/A_Migration_final/bin/common/props_1.dat 但正確的URL是 C:\用戶\ IBM_ADMIN \工作區\ A_Migration_final \ src \ common \ props.dat 它在bin文件中寫入,你認爲它會在查詢時給出正確的值嗎? –