How to write text to file in java

This tutorial shows you how to write some text into simple text file using java.

Write some text content is common task related to a text file. We can write the text content into any text file using FileWriter class in java. The FileWriter class has one constructor, where it accept a file and one boolean value, if the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Below is the example code of write some text in the end of text file.

package com.java.connect.io;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

//How to write text to file in java
public class WriteTextToFileExample {
	public static void main(String[] args) throws IOException {
		// Get the File Object by passing file name
		File file = new File("example.txt");

		// Get the fileWrite object by passing file and append
		// as true
		FileWriter fileWrite = new FileWriter(file, true);
		// Write some content in the file
		fileWrite.write("This is example content in the file at line one"
				+ System.getProperty("line.separator"));
		fileWrite.write("This is example content in the file at line two"
				+ System.getProperty("line.separator"));
		// Flush after write
		fileWrite.flush(); 
		// Close writer
		fileWrite.close();
	}
}

The output of the above example will write below content inside example.txt file as:

This is example content in the file at line one
This is example content in the file at line two