我有一个包含此信息的文本文件,每行信息从GUI追加到文本文件的新行:
1,Bday,12/23/1990,hills,description
2,Christmas,25/12/2018, home, presents are given and taken
3, easter,12/12/1996, inside an egg, the easter bunny is here
我希望替换某一行,因为该行以id开头,我的程序当前会删除所有数据并且不会替换任何内容。寻找有关如何修复并进行此文本行替换的答案。
private void updateEventActionPerformed(java.awt.event.ActionEvent evt) {
String id = idInput.getText();
String eventName = nameInput.getText();
String date = dateInput.getText();
String location = locationInput.getText();
String description = descriptionInput.getText();
String newContent = (id+","+ eventName +","+ date +","+ location +","+ description);
String oldText="";
String line;
try
{
BufferedReader br = new BufferedReader(new FileReader(events));
BufferedWriter write = new BufferedWriter(new FileWriter(events));
while((line = br.readLine()) != null)
{
oldText += line+"\r\n";
}
br.close();
String update = oldText.replaceAll(String update = oldText.replaceAll(line.startsWith(id), newContent);
write.write(update);
write.close();
JOptionPane.showMessageDialog(Event.this, "Event Updated");
}
catch(Exception err)
{
JOptionPane.showMessageDialog(Event.this, "Event not Updated");
JOptionPane.showMessageDialog(Event.this, err.getMessage());
}
}
答案 0 :(得分:0)
创建FileWrite会截断现有文件。您将首先读取文件,然后关闭FileReader并创建FileWriter,然后进行编写。