In this java tutorial, you will learn about how to append data to an existing text file from a Java program. This means you can write new content at the end of the file. One of the common examples of appending text to file is logging.
We can add a string to an existing file in Java by using FileWriter, which offers the ability to open a file in append mode. The FileWriter class in Java is used to save character-oriented data to a file. It can be used for the efficient writing of single characters, arrays, and strings in a file.
Here are the steps to append data to an existing file.
- Create a File object by passsing the path of the existing text file.
- Create an instance of FileWriter object by passing absolute path of existing file and a true boolean value to represent append mode.
- Write the text data to the file using the write() method of FileWriter object.
import java.io.File;
import java.io.FileWriter;
public class AppendDataInFile {
public static void main(String args[]) throws Exception {
String data = "Sample string to append";
File existingFile = new File("techcrashcourse.txt");
if(!existingFile.exists()) {
existingFile.createNewFile();
}
FileWriter fileWritter = new FileWriter(
existingFile.getAbsolutePath(),true);
fileWritter.write(data);
fileWritter.close();
System.out.println("Append Complete");
}
}
Output
Append Complete