关闭后,Java PrintWriter不会附加到现有的.txt文件中

时间:2014-10-22 09:18:48

标签: java file text append printwriter

我在尝试附加到现有文本文件时遇到了一些问题。

似乎没有附加行文字。到目前为止,我有这种方法:

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替换了f.getName(),并在pw.close()之前添加了pw.flush

1 个答案:

答案 0 :(得分:0)

我认为你的displayContent(File)函数有bug。

上面的代码会附加到文件中。 查看文件以查看是否附加了任何内容。

每次添加一行时,是否还需要创建PrintWriter对象? 如果要添加许多连续行,请尝试通过创建静态/最终对象来使用单个PrintWriter / BufferedWriter对象。