How to write to file in Java – BufferedWriter

In Java, we can use BufferedWriter to write content into a file.


	// jdk 7
	try (FileWriter writer = new FileWriter("app.log");
		 BufferedWriter bw = new BufferedWriter(writer)) {

		bw.write(content);

	} catch (IOException e) {
		System.err.format("IOException: %s%n", e);
	}
Note
If possible, uses Files.write instead, one line, simple and nice.


	List<String> list = Arrays.asList("Line 1", "Line 2");
    Files.write(Paths.get("app.log"), list);

Read Files.write examples

1. BufferedWriter

Write content into a file.

FileExample1.java

package com.mkyong;

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

public class FileExample1 {

    public static void main(String[] args) {

        String content = "This is the content to write into file\n";

        // If the file doesn't exists, create and write to it
		// If the file exists, truncate (remove all content) and write to it
        try (FileWriter writer = new FileWriter("app.log");
             BufferedWriter bw = new BufferedWriter(writer)) {

            bw.write(content);

        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);
        }

    }
}

Output

app.log

This is the content to write into file

For Append mode, pass a true as second argument in FileWriter


	// If the file exists, append to it
	try (FileWriter writer = new FileWriter("app.log", true);
		 BufferedWriter bw = new BufferedWriter(writer)) {

		bw.write(content);

	} catch (IOException e) {
		System.err.format("IOException: %s%n", e);
	}

2. BufferedWriter (Old School Style)

Before the JDK 7 try-resources, we need to handle the close() manually. A painful memory, let see this :

FileExample2.java

package com.mkyong;

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

public class FileExample2 {

    public static void main(String[] args) {

        BufferedWriter bw = null;
        FileWriter fw = null;

        try {

            String content = "This is the content to write into file\n";

            fw = new FileWriter("app.log");
            bw = new BufferedWriter(fw);
            bw.write(content);

        } catch (IOException e) {
            System.err.format("IOException: %s%n", e);
        } finally {
            try {
                if (bw != null)
                    bw.close();

                if (fw != null)
                    fw.close();
            } catch (IOException ex) {
                System.err.format("IOException: %s%n", ex);
            }
        }
    }
}

Output

app.log

This is the content to write into file

References

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
26 Comment threads
14 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
35 Comment authors
SanmkyongkabirJystinzSailendra Narayan Jena Recent comment authors
newest oldest most voted
Wasim Memon
Guest
Wasim Memon

thanks sir for nice tutorial but can you tell me why you have used both file writer and bufferwriter.

Brutus
Guest
Brutus

Or, much simpler and not wasting any time:

List lines; // The lines in your file
Path file = Paths.get("your-path-here");
Files.write(file, lines);

Christian Munch Hammervig
Guest
Christian Munch Hammervig

when Iclose the program and open it again it overwrites all and only place the new entry but i want all data to remain but I can’t find out what is wrong try { File file = new File(“driver.txt”); String drive = “”; // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } for (int i = 0; i < driverList.size(); i++) { drive = driverList.get(i).getName() + " " + driverList.get(i).getDistance() + " " + driverList.get(i).getCountry() + " " + driverList.get(i).getCity() + " " + driverList.get(i).getTime(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw);… Read more »

mohamed
Guest
mohamed

Hi, I want to ask you how can I create a file on another computer for example I m using windows and I try to create a file on linux connected to my network

trackback
Java I/O Tutorials | J2EE Web Development Tutorials

[…] Write file with BufferedWriter […]

Paul
Guest
Paul

Hi – Thanks for the sample. Would you happen to know if there is any reason to also close the FileWriter?

Also – Shouldn’t we be closing the streams in a finally clause since if an error occurs in the try we would never get to close()…

finally {
if(br != null) br.close();
if(fw != null) fr.close();
}

Thank you…

Faisal
Guest
Faisal

Don’t know why the above code is not working for me. Here a little change in code (given below) did resolve my issue. import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; public class WriteToFileExample { public static void main( String[] args ) { BufferedWriter bw = null; try{ String content = "This is the content to write into file"; File file =new File("C:/filename.txt"); //if file doesnt exists, then create it if(!file.exists()){ file.createNewFile(); } //Construct the BufferedWriter object bw = new BufferedWriter(new FileWriter(file)); //Start writing to the output stream bw.write(content); bw.close(); System.out.println("Done"); }catch(IOException e){ e.printStackTrace(); } } }

reza
Guest
reza

Hi
whats different between “FileOutputStream” and “BufferedWriter “?
which one do you recommend to use?

thanks a lot

best regards

Philip
Guest
Philip

… can someone please help me with this problem , when the user is inputting the information it isn’t saving in the text file —————————————————————————————— String name1 = JOptionPane.showInputDialog (“Enter Name & Surname”); BufferedWriter bufferedWriter = null; try { bufferedWriter = new BufferedWriter(new FileWriter(“Teldir.txt”)); bufferedWriter.write(“Writing line one to file”); bufferedWriter.newLine(); bufferedWriter.write(“Writing line two to file”); } catch (FileNotFoundException ex) { ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } finally { } try {

Jayanth
Guest
Jayanth

Thank you a lot. Whenever, i get a doubt or need something, i just search it in your website. It’s really helpful.

anupam ghosh
Guest
anupam ghosh

Hi Mkyong,

Thank you for all your posts. This is really very helpful as quick reference.

Regards
Anupam

joe
Guest
joe

great help, always result number one when Googling 🙂

sankar
Guest
sankar

Thank you 🙂
Mykong

your blog has cleared so many of my confusions……..

will you help me in reading an xml file and printing parent nodes and child nodes

for example

expected output:
employee/name/firstname
employee/name/laststname
employee/age

NG
Guest
NG

hi everyone im actually new hea and im stuck wit bufferedreader codes can anyone help me plss

NG
Guest
NG

wooops not reader its writer lol

Jens Preem
Guest
Jens Preem

Hi, thank you for your pieces of code. I am just starting to learn Java – which is kind of whole different bag comapred to Perl and Python I have used previously and your website has some really clear examples. As I am now getting all giddly with the OO side of everything I thought Id try to do some text file processing that I have done with Perl in Java. In Perl it has been quite easy to put down read-line->do-stuff(reformat-line)->write-formatted-line.(close) I see a class here that reads a file line by line and has embedded do stuff-print the… Read more »

A's
Guest
A's

Thnaks!!!

Alexandra
Guest
Alexandra

Hi guys, can anyone please help me with this? I’m trying to write 10 lines in a .doc file with a buffered writer. Each line contains a string and a number, as below:

for(int count=0;count<=9;count++){
br.write(accents[count] + ": ");
br.write(results[count] + "%\n");
}

accents is an array of 10 strings, and results is an array of 10 float numbers. How can I change the font color (to red, for example), when results[count] is bigger than a fixed value?

heinrich
Guest
heinrich

thanks sir mkyong. you help me a lot.

rishi
Guest
rishi

thanxx Mkyong 🙂 its really helpful…

Batoor
Guest
Batoor

for which purpose we use file.getAbsoluteFile?

Sailendra Narayan Jena
Guest
Sailendra Narayan Jena

Hi mkyong one query i have can we override BufferedWriter write() method into our class?

Jystinz
Guest
Jystinz

how to set permission file

kabir
Guest
kabir

Thanks a lot for your easy to understand guide.

kishan
Guest
kishan

can anyone teach me java
🙁

QuickSilver
Guest
QuickSilver

Thank you very much. You are like a Java Dictionary for me.