java

How to append content to an existing file in Java

In this tutorial, we are going to see how to add content to an existing file in Java. In Java, you can use FileWriter(file, true) to add new content at the end of a file.
 

How to append content to an existing file in Java
import java.io.*;

public class Main {
	public static void main(String[] args) {

		BufferedWriter bw = null;
		FileWriter fw = null;

		try {
			String data = "Welcome To StackHowTo!";

			File file = new File("C:\\Users\\PC\\Desktop\\bb.txt");

			// if the file does not exist, create it
			if (!file.exists()) {
				file.createNewFile();
			}

			// Append the content to the existing file
			fw = new FileWriter(file.getAbsoluteFile(), true);
			bw = new BufferedWriter(fw);

			bw.write(data);

			bw.close();
			fw.close();

		} catch (IOException e) {
			e.printStackTrace();
		} 
	}
}
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *