我想知道為什么我的程序會(huì)覆蓋文本文件中的現(xiàn)有文本而不是添加新的文本行?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."); } }}
1 回答

莫回?zé)o
TA貢獻(xiàn)1865條經(jīng)驗(yàn) 獲得超7個(gè)贊
該代碼會(huì)覆蓋該文件,因?yàn)槟鷽](méi)有OpenOption
在newBufferedWriter()
調(diào)用時(shí)指定 an 。
正如javadoc所說(shuō):
如果不存在任何選項(xiàng),則此方法的工作方式就像存在
CREATE
、TRUNCATE_EXISTING
和WRITE
選項(xiàng)一樣。換句話說(shuō),它打開(kāi)文件進(jìn)行寫(xiě)入,如果文件不存在則創(chuàng)建文件,或者如果存在則最初將現(xiàn)有文件截?cái)?code>regular-file為大小。0
嘗試:
?Files.newBufferedWriter(outFilePath,?StandardOpenOption.CREATE, ??????????????????????????????????????StandardOpenOption.APPEND, ??????????????????????????????????????StandardOpenOption.WRITE)
或者,如果文件必須已經(jīng)存在,如果不存在則失?。?/p>
?Files.newBufferedWriter(outFilePath,?StandardOpenOption.APPEND, ??????????????????????????????????????StandardOpenOption.WRITE)
寫(xiě)入新文件,如果文件已存在則失敗
?Files.newBufferedWriter(outFilePath,?StandardOpenOption.CREATE_NEW, ??????????????????????????????????????StandardOpenOption.WRITE)
添加回答
舉報(bào)
0/150
提交
取消