2014-10-30 63 views
0

我想在屬性文件中保留一些屬性,以防程序運行期間發生更改。現在我試圖這樣做:Java:在類路徑上加載和編輯屬性文件

Properties properties = new Properties(); 

    try (FileInputStream in = new FileInputStream("classpath:app.properties")) { 
     properties.load(in); 
    } catch (IOException e) { 
     logger.error("", e); 
    } 

    properties.setProperty("word", "abc"); 

    try (FileOutputStream out = new FileOutputStream("classpath:app.properties")) { 
     properties.store(out, null); 
    } catch (IOException e) { 
     logger.error("", e); 
    } 

但它似乎並沒有工作。我究竟做錯了什麼?

+0

嗯,我試圖做同樣的事情,並注意到我的屬性並未實際加載。我無法獲得我在文件中定義的道具。 – pbespechnyi 2014-10-30 20:02:39

回答

1

如果文件與程序位於同一目錄中,則不需要classpath部分。

Properties properties = new Properties(); 

try (FileInputStream in = new FileInputStream("app.properties")) { 
    properties.load(in); 
} catch (IOException e) { 
    logger.error("", e); 
} 

properties.setProperty("word", "abc"); 

try (FileOutputStream out = new FileOutputStream("app.properties")) { 
    properties.store(out, null); 
} catch (IOException e) { 
    logger.error("", e); 
} 

否則,如果該文件是你的罐子內,你將不得不重新打包的jar

3

爲了能夠讀寫屬性文件,它是在resources文件夾(在標準的Maven項目結構)您可以使用此:

// of course, do not forget to close the stream, after your properties file has been read. 
properties.load(Runner.class.getClassLoader().getResourceAsStream("app.properties")); 

後修改過的屬性文件,您可以使用類似:

Runner.class.getClassLoader().getResource("app.properties").getFile() 

獲取絕對路徑給你的文件。

P.S.只是爲了確保你正在檢查正確的文件。您不應該檢查resources文件夾中的文件。修改後的文件將與您的課程放在根文件夾中,如targetout

0

如果你要堅持性文件處理通過類路徑 - 你當然可以使用下面的代碼,因爲它是,我認爲這是處理類路徑文件中兩個最簡單的方法 - 閱讀和寫作目的

try{ 

    InputStream in = this.getClass().getResourceAsStream("/suggest.properties"); 
    Properties props = new Properties(); 
    props.load(in); 
    in.close(); 


    URL url = this.getClass().getResource("/suggest.properties"); 
    File fileObject = new File(url.toURI()); 

    FileOutputStream out = new FileOutputStream(fileObject); 

    props.setProperty("country", "america"); 
    props.store(out, null); 
    out.close(); 

    }catch(Exception e) 
    { 
     System.out.println(e.getMessage()); 
    }