[英]Rewrite a specific line in a txt file
我正在嘗試重寫txt文件中包含學生詳細信息的行。 文件中將列出學生的詳細信息,例如:
我試圖使用BufferedReader將Name2,20重寫為Name2,13,以查找具有Name2的行。 還有一個BufferedWriter用新文本替換該行,但事實證明代碼會將我的整個txt文件寫為null。
這是我的代碼:
String lineText;
String newLine = "Name,age";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
BufferedWriter bw = new BufferedWriter(new FileWriter(path,false));
while ((lineText = br.readLine()) != null){
System.out.println(">" + lineText);
String studentData[] = lineText.split(",");
if(studentData[0].equals(Name2)){
bw.write(newLine);
}
System.out.println(lineText);
}
br.close();
bw.close();
}
catch (IOException e) {
e.printStackTrace();
}
誰能告訴我如何在txt文件中重寫特定行?
最簡單的方法是讀取整個文件,並將其存儲在變量中。 讀取當前文件時替換有問題的行。
就像是:
String lineText;
String newLine = "Name,age";
try {
BufferedReader br = new BufferedReader(new FileReader(path));
BufferedWriter bw = new BufferedWriter(new FileWriter(path,false));
String currentFileContents = "";
while ((lineText = br.readLine()) != null){
System.out.println(">" + lineText);
String studentData[] = lineText.split(",");
if(studentData[0].equals("Name2")){
currentFileContents += newLine;
} else {
currentFileContents += lineText;
}
}
bw.write(currentFileContents);
br.close();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.