簡體   English   中英

Java PrintWriter在關閉后不會追加到現有的.txt文件中

[英]Java PrintWriter doesn't append to existing .txt file after closing

嘗試附加到現有文本文件時遇到了一些問題。

它似乎沒有追加行文本。 到目前為止,我已經有了這種方法:

public static void addLine(File f, String line) {
    try {
        FileWriter fw = new FileWriter(f.getName(), true);
        BufferedWriter buffer = new BufferedWriter(fw);
        PrintWriter pw = new PrintWriter(buffer);
        pw.println(line);
        pw.close();

    } catch (IOException e) {
        System.err.println("IOException: " + e.getMessage());

    }
}

在我的主要工作中,我有以下幾點:

public static void main(String[] args) {
    File f = new File("adresOfFile");
    if (f.exists() && !f.isDirectory()) {
        System.out.println("File " + f.getName() + " exists!");
        System.out.println("\n" + "Path: " + f.getAbsolutePath());
        System.out.println("\n" + "Parent: " + f.getParent());
        System.out.println("\n" + "--------------CONTENT OF FILE-------------");
        addLine(f, "");
        addLine(f, "The line to append");
        try {
            displayContent(f);
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    } else {
        System.out.println("File not found");
    }
}

當我運行程序時,似乎沒有給出任何錯誤。 運行該程序應打印出現有文本(displayContent),這是在追加(addLine)之后完成的。 但是,當我運行它時,它僅顯示現有文本,而沒有附加行。

它也不會顯示在文本文件中。 我試圖放一個System.out.println(); 在方法中,它會打印出來,所以我知道它正確地運行了方法,只是沒有追加。

編輯AWNSER:將f.getName()替換為f,並在pw.close()之前添加pw.flush

我認為您的displayContent(File)函數存在錯誤。

上面的代碼確實附加到了文件中。 查看文件以查看是否附加了任何內容。

您還需要在每次添加一行時創建PrintWriter對象嗎? 如果要添加許多連續行,請嘗試通過創建靜態/最終對象來使用單個PrintWriter / BufferedWriter對象。

暫無
暫無

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

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