简体   繁体   中英

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

I think that your displayContent(File) function has bugs.

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? If there are many continuous lines to be appended, try using a single PrintWriter/ BufferedWriter object by creating a static/final object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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