Write to File in Java using BufferedWriter


Let's see step by step how to make use of the java.io.BufferedWriter class to write to a file in Java.

  1. First let's create a String that holds data that we need to write to a file.
    String data = "Some data to write to a file";
  2. Next, let's say we want to write to a file named data.txt
    String fileName = "data.txt";
  3. Next we need to create an object of java.io.FileWriter and pass in the fileName and a boolean flag to say if we want text to be appended to the file or not.
    FileWriter fileWriter = new FileWriter(fileName, true);

    Params:

    fileName – String The system-dependent filename.
    append – boolean If true, then data will be written to the end of the file rather than the beginning.

    FileWriter throws IOException

  4. Now we can make use of the object of java.io.BufferedWriter and pass the FileWriter object to its constructor. BufferedWriter will create a buffered character-output stream which is a file in our case.
  5. Next, make use of the write() method from BufferedWriter to write the String data to the file.
  6. Finally make sure to close the stream using the close() method.

Complete Code:
package org.code2care.example;

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

/**
 * <pre>
 * Example: Write a file using BufferedWriter
 *
 * Author: Code2care.org
 * Version: v1.0
 * Date: 5th July 2023
 * </pre>
 */
public class WriteFileUsingBufferedWriterExample {

    public static void main(String[] args) {

        String data = "Some data to write to a file";
        String fileName = "data.txt";

        try (FileWriter fileWriter = new FileWriter(fileName, true);
             BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
            bufferedWriter.write(data);
        } catch (IOException ioException) {
            System.out.println("Error occurred writing the file!");
        }
    }
}

Modified the code slightly to make us of try-with-resouce feature that was introduced in Java 7.

Output:
Write to File in Java using BufferedWriter - Output

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap