How to Append Data to a File in Java
Appending means adding data at the end of an existing file without deleting or overwriting the previous content.
In Java, you can append text to a file using FileWriter
in append mode.
Append का मतलब है पहले से मौजूद file के अंत में नया data जोड़ना, बिना पुराने content को हटाए या overwrite किए।
Java में, हम FileWriter
को append mode में use करके ऐसा कर सकते हैं।
Java Example to Append to a File
import java.io.FileWriter;
import java.io.IOException;
public class AppendToFile {
public static void main(String[] args) {
try {
// Open file in append mode (true means append)
FileWriter writer = new FileWriter("example.txt", true);
// Write new content at the end of the file
writer.write("This is new appended content.\n");
// Close the writer to save changes
writer.close();
System.out.println("Data appended successfully.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Explanation:
- FileWriter(filename, true): The second argument
true
enables append mode. Iffalse
or omitted, it overwrites the file. - writer.write(...): Adds the given string at the end of the file.
- writer.close(): Always close the writer to flush data and release resources.
- Try-catch block: Handles IOException in case the file is missing or there is a write error.
Expected File Behavior
If example.txt
initially contains:
Hello World!
After running the program, the file content will be:
Hello World! This is new appended content.
Notes:
- If the file does not exist,
FileWriter
will create it. - Append mode (
true
) preserves existing file data. - Always close streams or use try-with-resources (Java 7+) to avoid resource leaks.