简体   繁体   English

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

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

I've run into some problems trying to append to an existing text file. 尝试附加到现有文本文件时遇到了一些问题。

It doesn't seem to append a line text. 它似乎没有追加行文本。 So far i've got this method: 到目前为止,我已经有了这种方法:

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());

    }
}

and in my main i've got the following: 在我的主要工作中,我有以下几点:

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");
    }
}

When I run the program it doesn't seem to give any errors. 当我运行程序时,似乎没有给出任何错误。 Running the program should print out the existing text (displayContent), which is done after appending (addLine). 运行该程序应打印出现有文本(displayContent),这是在追加(addLine)之后完成的。 But when I run it, it only shows the existing text, without the appended line. 但是,当我运行它时,它仅显示现有文本,而没有附加行。

It doesn't show up in the text file either. 它也不会显示在文本文件中。 I tried to put a System.out.println(); 我试图放一个System.out.println(); in the method, and it prints, so I know its running the method properly, just not appending. 在方法中,它会打印出来,所以我知道它正确地运行了方法,只是没有追加。

EDIT AWNSER: replaced f.getName() with f, and added pw.flush before pw.close() 编辑AWNSER:将f.getName()替换为f,并在pw.close()之前添加pw.flush

I think that your displayContent(File) function has bugs. 我认为您的displayContent(File)函数存在错误。

The above code does append to the file. 上面的代码确实附加到了文件中。 Have a look at the file to see if anything is appended. 查看文件以查看是否附加了任何内容。

Also do you need to create PrintWriter object each time you append a line? 您还需要在每次添加一行时创建PrintWriter对象吗? If there are many continuous lines to be appended, try using a single PrintWriter/ BufferedWriter object by creating a static/final object. 如果要添加许多连续行,请尝试通过创建静态/最终对象来使用单个PrintWriter / BufferedWriter对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM