Avatar ·

How to add text to an existing file in Java without overwriting its content?

Hello everyone! I'm a beginner Java developer and I've encountered a problem while working with files. I need to implement a logging function in my application: each event should be appended to the end of the log file, not overwrite it.\n\nThe problem is that I'm using FileWriter, but it creates a new file every time, destroying previous entries. Here's my current code:\n\n```java\nimport java.io.FileWriter;\nimport java.io.IOException;\n\npublic class Logger {\n public static void main(String[] args) {\n try {\n FileWriter writer = new FileWriter("log.txt");\n writer.write("First entry");\n writer.write("Second entry");\n writer.close();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n}\n```\n\nK