Friday, January 12, 2024

How to write to File in Java using BufferedWriter [Example]

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 types directly into a file like writeInt() to write integer values, writeFloat() to write floating-point values into a 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. Its println() method automatically adds a 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 also refer to Java: A Beginner's Guide by Herbert Schildt to start with Java. This book contains very good examples 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 the current directory. If the 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 the 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 filehandles 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.

If you are running in Java 1.7 then you can use the 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 

When writing to a file in Java using BufferedWriter, it's crucial to keep a few key considerations in mind. First, ensure that the file path and name are accurate, and that the application has the necessary permissions to write to the specified location. 

Second, use a try-with-resources statement to automatically close the BufferedWriter and release system resources after writing is complete, preventing potential memory leaks. 

Here are few more things which are worth noting:

 1) Use FileWriter class if you want to read a text file in the 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 than writing one byte at a time.

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

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

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

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 the 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)

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 the individual features of Java.

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.