【问题标题】:Java PrintWriter doesn't append to existing .txt file after closing关闭后 Java PrintWriter 不会附加到现有的 .txt 文件
【发布时间】:2014-12-17 16:59:12
【问题描述】:

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

它似乎没有附加一行文本。到目前为止,我已经有了这个方法:

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();在方法中,它会打印出来,所以我知道它正确地运行了方法,只是没有附加。

EDIT AWNSER:将 f.getName() 替换为 f,并在 pw.close() 之前添加 pw.flush

【问题讨论】:

    标签: java file text append printwriter


    【解决方案1】:

    我认为您的 displayContent(File) 函数有错误。

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

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

    【讨论】:

    • 当我查看文件时没有任何更改,也没有添加任何行。没有连续的行,我只需要添加一个空行和一个测试行。
    • 你得到什么输出?你确定你写的是文件的名称/路径吗?该代码对我有用。这是link 此代码附加到与 moja.java 文件位于同一位置的文件“a”。
    • 并使用FileWriter(File file, boolean append)构造函数代替 FileWriter(String, boolean) 并在 pw.close() 之前执行 pw.flush()
    • 有效!我用 f 替换了 f.getName(),并在 pw.close() 之前添加了 pw.flush()。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 2020-02-21
    相关资源
    最近更新 更多