第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

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

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

陪伴而非守候 2023-10-19 14:50:54
我想知道為什么我的程序會(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)有OpenOptionnewBufferedWriter()調(diào)用時(shí)指定 an 。

正如javadoc所說(shuō):

如果不存在任何選項(xiàng),則此方法的工作方式就像存在CREATE、TRUNCATE_EXISTINGWRITE選項(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)


查看完整回答
反對(duì) 回復(fù) 2023-10-19
  • 1 回答
  • 0 關(guān)注
  • 94 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)