[英]Replacing a specific string from a text file in Java
我有一個這樣的文本文件:圖片
第一列代表用戶 ID,最后一列代表余額。 我想遍歷元素以找到特定的用戶 ID,然后更新他們的余額。 我已設法匹配用戶 ID 並使用掃描儀訪問余額,但我不確定如何使用新值更新文本文件中的余額。 這是我到目前為止編寫的代碼:
File file = new File("UserInfo.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
String info = sc.nextLine();
String data[] = info.split(" ");
//userId is a function argument
if(String.valueOf(userId).equals(data[0])){
//I want to update the balance in the text file with a new value here
}else{
continue;
}
}
sc.close();
您似乎想創建一個 CSV 文件。 我的建議是使用“;” 作為 split() 命令的分隔符,如果文件不是太大,則讀取整個文件,將其放入 Strings 的 arrayList 中,然后對其進行操作,最后從 arrayList 重寫整個文件。 否則你必須使用 RandomAccess class
替換文件中的字符串並不是那么簡單。 您必須讀取整個文件並重寫您想要保持不變的部分。 只有當比較userID
和data[0]
的條件滿足時,你才會使用replace()
function 來改變用戶余額。
您的文件基本上是 CSV 文件,其中空格作為行分隔符,如前所述,將文件內容存儲在數組或BufferedReader
中,更改適當的行,然后導出回 CSV。
File file = new File("UserInfo.txt");
Scanner sc = new Scanner(file);
ArrayList<String> items = new ArrayList<String>();
while(sc.hasNextLine()){
String info = sc.nextLine();
String data[] = info.split(" ");
if(String.valueOf(currentUser.getAccountNumber()).equals(data[0])){
data[3] = String.valueOf(currentUser.getBorrowBalance());
//Updating the balance in ArrayList
}else{
continue;
}
for(int i=0; i<data.length; i++){
items.add(data[i]);
}
}
PrintWriter pw = new PrintWriter(file);
for(int j=0; j<items.size(); j++) {
pw.printf("%s ", items.get(j));
if(j%3==0) pw.println(); //Going to new line after writing 4 elements to text file
}
pw.close();
sc.close();
所以這些是我到目前為止所做的改變。 我嘗試獲取元素,修改天平並將更新的值放入 arraylist 中。 然后使用 PrintWriter 將它們放入文本文件中。 但是當我調用這個 function 時,我總是得到一個空的文本文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.