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
>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.