How to Write a File Line by Line in Java?

This post summarizes the classes that can be used to write a file.

1. FileOutputStream

public static void writeFile1() throws IOException {
	File fout = new File("out.txt");
	FileOutputStream fos = new FileOutputStream(fout);
	BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
	for (int i = 0; i < 10; i++) {

This example use FileOutputStream, instead you can use FileWriter or PrintWriter which is normally good enough for a text file operations.

2. FileWriter

public static void writeFile2() throws IOException {
	FileWriter fw = new FileWriter("out.txt");
	for (int i = 0; i < 10; i++) {

3. PrintWriter

public static void writeFile3() throws IOException {
	PrintWriter pw = new PrintWriter(new FileWriter("out.txt"));
	for (int i = 0; i < 10; i++) {

4. OutputStreamWriter

public static void writeFile4() throws IOException {
	File fout = new File("out.txt");
	FileOutputStream fos = new FileOutputStream(fout);
	OutputStreamWriter osw = new OutputStreamWriter(fos);
	for (int i = 0; i < 10; i++) {

5. Their Differences

From Java Doc:

FileWriter is a convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.

PrintWriter prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.

The main difference is that PrintWriter offers some additional methods for formatting such as println and printf. In addition, FileWriter throws IOException in case of any I/O failure. PrintWriter methods do not throws IOException, instead they set a boolean flag which can be obtained using checkError(). PrintWriter automatically invokes flush after every byte of data is written. In case of FileWriter, caller has to take care of invoking flush.

Category >> I/O  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. Preethi on 2014-9-11

    How to write new line by using FileWriter class???

  2. Sato on 2014-10-6

    I think you can use “n” in your string which is a “new line character”. Like:
    FileWriter fw = …
    fw.write(“line 1n” + “line 2n + “line 3n”);

  3. Abc on 2015-4-17

    Sato: Its an error.

  4. Danny on 2015-10-14

    I found this to be extremely helpful. I only wish that more guides were as clear, concise and just as simple as this one.

  5. Shivam Singh on 2015-11-19

    Well explain examples and also visit nice example for create file in java

  6. RF Kill on 2016-1-17

    Awesome article man..Thanks!

Leave a comment