[英]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.