我正在尝试替换文件中的特定文本行。我遇到了一个问题,因为以下代码更改了每一行代码中的每个ID。
String filepath = "data.txt";
String newID = textFId.getText()
String newRoadName = textFRname.getText();
String newRoadNumber = textFRnumber.getText();
String newCarType = textFCartype.getText();
String tempFile = "datatemp.txt";
File oldFile = new File(filepath);
File newFile = new File(tempFile);
String ID = "";
String RoadName = "";
String RoadNumber = "";
String CarType = "";
try {
FileWriter fw = new FileWriter(tempFile, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
x = new Scanner(new File(filepath));
x.useDelimiter("[,\n]");
while(x.hasNext()) {
ID = x.next();
RoadName = x.next();
RoadNumber = x.next();
CarType = x.next();
if(ID.equals(newID)) {
System.out.println(newID);
pw.println(newID + "," + newRoadName + "," + newRoadNumber + "," + newCarType);
} else {
pw.println(ID + "," + RoadName + "," + RoadNumber + "," + CarType);
System.out.println(newID);
}
}
x.close();
pw.flush();
pw.close();
oldFile.delete();
File dump = new File(filepath);
newFile.renameTo(dump);
}
catch (Exception e3){
System.out.println("UPDATE ERROR!!");
}
我的文本文件是这个:
1,PO,100,GB
2,PO,101,GB
3,PO,102,GB
4,PO,103,GB
当我更新一行时,我的输出应该是这样:
1,PO,100,GB
2,PO,101,GB
3,PO,102,GB
4,PO,104,GB
但是我的输出结果是这样的:
4,PO,104,GB
4,PO,104,GB
4,PO,104,GB
4,PO,104,GB
答案 0 :(得分:0)
这是我们不关注的部分:
String newID = textFId.getText()
String newRoadName = textFRname.getText();
String newRoadNumber = textFRnumber.getText();
String newCarType = textFCartype.getText();
来自哪里的textFId,textFRname,textFRnumber和textFCartype?