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.

 1import java.io.BufferedWriter;
 2import java.io.FileWriter;
 3import java.io.IOException;
 4
 5public class FileWriteSample {
 6
 7    public static void main(String [] argv) throws IOException {
 8
 9        boolean append = true;
10
11        try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("data/outfile.txt", append))) {
12            bufferedWriter.write("Hello, I have written some text\n"); // A line is written
13            bufferedWriter.write('g'); // A single character is written
14        }
15    }
16}
17

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.

comments powered by Disqus