亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Java,如何編寫或添加而不是覆蓋文本文件?

Java,如何編寫或添加而不是覆蓋文本文件?

陪伴而非守候 2023-10-19 14:50:54
我想知道為什么我的程序會覆蓋文本文件中的現有文本而不是添加新的文本行?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 回答

?
莫回無

TA貢獻1865條經驗 獲得超7個贊

該代碼會覆蓋該文件,因為您沒有OpenOptionnewBufferedWriter()調用時指定 an 。

正如javadoc所說:

如果不存在任何選項,則此方法的工作方式就像存在CREATETRUNCATE_EXISTINGWRITE選項一樣。換句話說,它打開文件進行寫入,如果文件不存在則創建文件,或者如果存在則最初將現有文件截斷regular-file為大小。0

嘗試:

?Files.newBufferedWriter(outFilePath,?StandardOpenOption.CREATE,
??????????????????????????????????????StandardOpenOption.APPEND,
??????????????????????????????????????StandardOpenOption.WRITE)

或者,如果文件必須已經存在,如果不存在則失?。?/p>

?Files.newBufferedWriter(outFilePath,?StandardOpenOption.APPEND,
??????????????????????????????????????StandardOpenOption.WRITE)

寫入新文件,如果文件已存在則失敗

?Files.newBufferedWriter(outFilePath,?StandardOpenOption.CREATE_NEW,
??????????????????????????????????????StandardOpenOption.WRITE)


查看完整回答
反對 回復 2023-10-19
  • 1 回答
  • 0 關注
  • 95 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號