Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Appending to file in static methods keep rewriting the whole file in Java

I have a static method in which I want to write something to a file, but it keeps rewriting the whole file.

public static void log(Class called, String functionName, String problem) {
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter("log.txt"));
            bw.append(LocalDateTime. now() + " - " + called.getCanonicalName() + " - " + functionName + " - " + problem + "\n");
            bw.close();
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
    }

The file in which I am writing keeps rewriting the first line

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The default constructor of FileWriter will rewrite the file. There is an alternative constructor that you can use:

BufferedWriter bw = new BufferedWriter(new FileWriter("log.txt", true));

Also take a look at the documentation for the append method because it does something different from what you think.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading