Java,如何编写或添加而不是覆盖文本文件?
问题描述 投票:0回答:1
我想知道为什么我的程序会覆盖文本文件中的现有文本,而不是添加新的一行文本吗?public class WriteToFile {
public void registerTrainingSession(Customer customer) {
Path outFilePath = Paths.get("C:\\Users\\Allan\\Documents\\Nackademin\\OOP\\Inlämningsuppgift2\\visits.txt");
try (BufferedWriter save = Files.newBufferedWriter(outFilePath)) {
String trainingSession = String.format("Member: %s %s\nPersonalnumber: %s\nTraining session date: %s\n", customer.getFirstName(),
customer.getLastName(), customer.getPersonalNumber(), LocalDate.now());
save.write(trainingSession);
save.flush();
}
catch (NullPointerException e) {
JOptionPane.showMessageDialog(null, "Customer info is missing!");
}
catch (IOException e) {
JOptionPane.showMessageDialog(null, "File could not be created.");
}
}
}
java
text-files
bufferedwriter
1个回答
0
投票
由于您未在OpenOption调用中指定OpenOption,因此代码覆盖了文件。如果没有选项,则此方法就像存在newBufferedWriter(),javadoc和CREATE选项一样工作。换句话说,它将打开要写入的文件,如果不存在则创建文件,或者如果存在,首先将现有的TRUNCATE_EXISTING截断为WRITE的大小] >>。
尝试:regular-file
或者如果文件必须已经存在,则失败;]0
写入新文件,如果已经存在则失败Files.newBufferedWriter(outFilePath, StandardOpenOption.CREATE,
StandardOpenOption.APPEND,
StandardOpenOption.WRITE)
热门问题