簡體   English   中英

Java BufferedWriter-newLine()方法

[英]Java BufferedWriter - newLine() method

我已經遇到了一段時間,並測試了我能想到的所有可能性。 不幸的是,這些可能性不起作用。

基本上,我試圖使用Java中的BufferedWriter寫入.txt文件。 我需要此設置,以便可以在每條數據之間插入一行。 想象這是從Java產生的文本文件,它應該看起來像這樣:

line1

line2

這是我的代碼:

public static void main(String[] args) {
    Path path = Paths.get("test.txt");

    if (!Files.exists(path)) {
        try {
            Files.createFile(path);
        } catch (IOException e) {
            System.out.println("Error in creating test.txt! Read the stacktrace 
            below.");
            e.printStackTrace();
        }
    }

    Charset charset = Charset.forName("UTF-8");
    try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) {
        String string = "line1";
        writer.write(string, 0, string.length());
        writer.newLine();
        writer.newLine();

        writer.flush();
    } catch (IOException e) {
        System.out.println("Unable to write to file! Read the StackTrace below.");
        e.printStackTrace();
    }

    try (BufferedWriter writer = Files.newBufferedWriter(path, charset)) {
        String string = "line2";
        writer.write(string, 0, string.length());

        writer.flush();
    } catch (IOException e) {
        System.out.println("Unable to write to file! Read the StackTrace below.");
        e.printStackTrace();
    }
}

這樣的輸出將產生一個文本文件,如下所示:

line2

現在,我知道我可以將兩個try / catches組合在一起,並且可以正常工作。 但這只是測試的表示; 在我的真實代碼中,我需要單獨執行此操作,以便每當觸發特定事件時就可以在.txt文件中進行寫入。

基本上,除非我在它們之后直接編寫文本,否則newLine()方法不會保存

一如既往地感謝您的幫助!

第二個BufferedWriter或更確切地說第二個隱式FileWriter覆蓋第一個創建的文件。

根據您的建議組合語句,或使用追加模式(在這種情況下效率低下)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM