Write text file in Java

There are couple of ways to write text data to file in Java. Here is one of the easy and simple way to do this. I used BufferedWriter with a FileWriter object. Since the BufferedWriter implements Closable interface, and hope we all are using Java 7 or above, so we can leverage the try-with-resource to automatically close it once the data has written.

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriteSample {

    public static void main(String [] argv) throws IOException {

        boolean append = true;

        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("data/outfile.txt", append))) {
            bufferedWriter.write("Hello, I have written some text\n"); // A line is written
            bufferedWriter.write('g'); // A single character is written

Note: You can decide whether to append or overwrite the data to the file by altering the append boolean flag. If you do not specify the append parameter while constructing the FileWriter, the file is overwritten.

Hansaraj avatar
About Hansaraj
Hansaraj is a Software Engineer experienced in Java, Groovy, JavaScript, SQL, C#, C++
comments powered by Disqus