How to Append to File in Java: Simple Guide with Examples
To append text to a file in Java, use
FileWriter with the constructor's second parameter set to true. This tells Java to add new content at the end of the file instead of overwriting it.Syntax
Use FileWriter with the second argument true to enable appending. Wrap it in BufferedWriter for efficient writing.
FileWriter(String fileName, boolean append):append = trueadds to file end.BufferedWriter(Writer out): buffers output for better performance.
java
FileWriter fw = new FileWriter("filename.txt", true); BufferedWriter bw = new BufferedWriter(fw); bw.write("text to append"); bw.close();
Example
This example shows how to append multiple lines to a file named example.txt. It opens the file in append mode, writes two lines, and closes the writer.
java
import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class AppendToFileExample { public static void main(String[] args) { String filePath = "example.txt"; try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) { writer.write("Hello, this is the first appended line.\n"); writer.write("And this is the second appended line.\n"); System.out.println("Lines appended successfully."); } catch (IOException e) { System.err.println("Error writing to file: " + e.getMessage()); } } }
Output
Lines appended successfully.
Common Pitfalls
Common mistakes when appending to files include:
- Not setting
appendtotrue, which overwrites the file. - Forgetting to close the writer, causing data loss.
- Not handling
IOException, which can crash the program.
Always use try-with-resources or close streams in finally block.
java
/* Wrong way: overwrites file */ FileWriter fw = new FileWriter("file.txt"); // append=false by default fw.write("This will overwrite existing content."); fw.close(); /* Right way: appends to file */ FileWriter fwAppend = new FileWriter("file.txt", true); fwAppend.write("This will add to the file."); fwAppend.close();
Quick Reference
Remember these tips when appending to files in Java:
- Use
new FileWriter(fileName, true)to append. - Wrap
FileWriterinBufferedWriterfor efficiency. - Always close writers to save data.
- Handle
IOExceptionproperly.
Key Takeaways
Set the second parameter of FileWriter to true to append instead of overwrite.
Use BufferedWriter to improve writing performance.
Always close your writer to ensure data is saved.
Handle IOExceptions to avoid program crashes.
Try-with-resources is the safest way to manage file streams.