How to write to File in Java using BufferedWriter

You can use either OutputStream or Writer class in Java to write data to a file in Java. For example, you can use a combination of FileWriter and BufferedWriter to write text content into a text file in Java. If you want to write raw bytes consider using FileOutputStream class. Just remember that InputStream is used to read data and OutputStream is used to write data to file or socket. You can write anything to file e.g. String, integer, float values etc. Java provides DataOutputStream to write different data type directly into file e.g. writeInt() to write integer values, writeFloat() to write floating point values into file and writeUTF() to write String into File.  BufferedWriter, like its counterpart BufferedReader, allows you to perform buffered IO, which can drastically improve performance while reading large files.

Java provides many convenient wrapper classes for reading and writing data into files e.g. you can use PrintWriter to write data line by line into the file. It's println() method automatically adds line separator after each line.

Java 7 has also introduced even a brand new API known as new File API, which provides powerful methods to read the whole file in just one line. All in all, Java has got really good support to deal with files in Java and we will explore more of them in coming tutorials.

By the way, if you are a beginner and just started learning Java, I would recommend you to at least read one Java book to get a complete overview, later you can fine tune your knowledge by reading tutorials.

You can refer Java: A Beginner's Guide by Herbert Schildt to start with Java. This book contains very good example and comprehensive theory and most important it's up-to-date and covers even Java 8.





Java Program for writing into a File using BufferedWriter

Here is our sample program to write data into a file in Java. In this program, we are writing String to file using FileWriter and BufferedWrite class. I have not used PrintWriter just to demonstrate how to add line separator in Java, but this makes my code platform dependent because the different platform has different line separator e.g. in Windows line separator is \n but in UNIX-like system e.g. Linux line separator is \r\n.

In this example, we open a file called names.txt, remember we are not creating a file here we are just opening an existing file in current directory. If file would not be there then our code will throw FileNotFoundException. This is a little bit tricky but in Java new file is created using File.createFile() method and now by using new File() constructor. The File instance actually represents a path in the file system and that's why Java 7 has introduced a new class called Path which is equivalent to java.io.File of Java SE 6.

When you use FileWriter to write into the file it uses default character encoding of the platform, which may not be what you want. If that's the case then use OutputStreamReader to provide custom character encoding.  Anyway, once you have a FileWriter pointing to a file you are all set to write data into a file, but if you want to write large text then it's better to wrap this FileWriter inside a BufferedWriter.

This is actually implemented using Decorator pattern because you add new functionality using composition without modifying existing classes. Next, we use write() method of BufferdWriter class to write text data into a file. Once we are done we close the file using close() method. This will release the file handles acquired by our code.

See Core Java Volume 2 - Advanced Features by Cay S. Horstmann to learn more about IO classes in Java. He is the author of a couple of really useful books on Java Programming including Java SE 8.

How to write to a file in Java


If you are running in Java 1.7 then you can use automatic resource management feature to automatically close opened resources in Java e.g. FileWriter, BufferedWriter all would have closed as soon as you exist try block.

package filetutorial;

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

/**
 * How to write to a file in Java using BufferedReader.
 * 
 * @author java67
 */

public class WriteToFile{

    public static void main(String args[]) {

        // Writing to a file using BufferedWriter in Java
        try {
            FileWriter writer = new FileWriter("names.txt");
            BufferedWriter bwr = new BufferedWriter(writer);
            bwr.write("James");
            bwr.write("\n");
            bwr.write("Hobert");
            bwr.close();
            System.out.println("succesfully written to a file");
            
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

    }

}

Important points about writing into File in Java 

1) Use FileWriter class if you want to read a text file in platform's default character encoding, otherwise use OutputStreamWriter to provide custom character encoding. Also, use FileOutputStream if you want to write bytes to file in Java.

2) Use BufferedWriter to write large text, it's more efficient that writing one byte at a time.

3) Instead of appending \n after every line you can also use PrintWriter object as shown below :

PrintWriter pwr = new PrintWriter(bwr);
pwr.println("Sara");

This is actually much better than inserting line separator by yourself. It's platform independent because Java will automatically identify correct line separator depending upon where you are running this program. Inserting \n or \r\n is fragile and will not work across all platform.

4) Make sure to close the file and BufferedWriter once you are done with writing into the file. You can also use a try-with-resource statement from Java 7 to automatically close the file.

How to write data to File in Java using BufferedWriter



That's all about how to write data to a File in Java. You can write any data type of filing by using respective write method from DataInputStream class e.g. writeInteger() to write int, writeUTF() to write String etc. In this example, we have only written String to file using BufferedWriter. You can even wrap BufferedWriter to PrintWriter to conveniently write line by line into the file in Java by using popular methods like print() and println().

If you like this tutorial and hungry to learn more about how to deal with Files in Java, you can also check my following Java IO tutorial from this blog :
  • How to read Excel file in Java using Apache POI? (example)
  • How to read JSON File in Java? (solution)
  • 2 Ways to read a text file in Java? (examples)
  • How do you use Scanner class in Java? (example)
  • How to read the file in Java 8 in one line? (example)
  • How do I read InputStream as String in Java? (solution)
  • How to use BufferedReader class in Java? (demo)
  • How to read XML file in Java using JDOM Parser? (solution)
  • How do I read input from the console in Java? (example)

Good books to Learn Java from Start

As I said if you are just starting with Java then it's better to follow one good book and finish it from start to end. This will build your base and you will learn a lot more in a short time. Once you have that base built you can explore more about individual feature of Java. You can choose any of following book to start your journey with Java. 
  • Head First Java by Kathy Sierra (check here)
  • Core Java, Volume 1 9th Edition by Cay S. Horstmann (check here)
  • Java: A Beginner's Guide by Herbert Schildt (check here)


No comments:

Post a Comment