[英]How do I add properties to a properties file using Java?
我有一個真正的快速問題。 我有一個Java程序,其中使用了屬性文件。 該文件用於跟蹤程序的用戶。 我的問題是我不知道如何添加到文件。 我知道如何將現有屬性設置為值,但是我不知道如何在不覆蓋其他屬性的情況下添加更多屬性。
可以這么說,我希望該程序“注冊”用戶。 每當有新用戶“注冊”時,我都希望程序添加一個包含新用戶信息的新屬性。 我遇到了這個問題:示例:
File: numOfUsers=0
一個用戶注冊。 用戶名是“ c00lGuy”。 程序將其注冊到文件中:
File: numOfUsers=1 user1-username=c00lGuy
另一個用戶注冊。 她決定將其用戶名稱為“ theGr8Girl”。 程序注冊:
File: numOfUsers=2 user2-username=theGr8Girl
兩個用戶注冊后的文件:
File: numOfUsers=2 user2-username=theGr8Girl
如何防止程序覆蓋文件中的現有行? 似乎會擦除文件的內容,然后添加我告訴它的內容。 我不希望它刪除文件的內容。
我用來注冊屬性的代碼:
Properties prop = new Properties();
OutputStream output = null;
int userCount = getUserCount();
userCount++;
try {
output = new FileOutputStream(fileName);
// set the properties value
prop.setProperty("numOfUsers", String.valueOf(userCount));
prop.setProperty("user" + userCount + "-username", username);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null)
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
嘗試這樣的事情:
FileOutputStream out = new FileOutputStream(fileName);
props.setProperty("numOfUsers", 2);
...
props.store(out, null);
out.close();
屬性文件並不是真的適合這種用途,但是如果您的數據集足夠小,它將可以使用。
缺少的步驟是,您需要從磁盤讀取屬性,進行更改,然后將其保存回磁盤。
Properties props = new Properties();
try{
props.load(inputStream);
} finally {
inputStream.close();
}
props.setProperty(....);
try{
props.store(outputStream);
} finally {
outputStream.close();
}
請記住,這根本不適合任何類型的卷處理。 另外,如果您有兩個線程試圖同時更改屬性文件,則存在競爭情況。
如果您正在尋找輕量級的持久性存儲,我強烈建議mapdb 。
您的代碼每次都創建一個新的Properties
對象。 添加用戶時,請確保重用舊實例。
該文件中一行的典型格式為
user=hashedPassword
因此,請使用用戶名作為密鑰,並使用密碼作為值。 用戶數量不需要存儲,僅是屬性映射的大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.