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

Wasim Memon
Guest
Wasim Memon

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

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 »

Christian Munch Hammervig
Guest
Christian Munch Hammervig

I have solved the problem
I changed the line saying : FileWriter fw = new FileWriter(file.getAbsoluteFile());
to: FileWriter fw = new FileWriter(file, true);
so now it does not overwrite the old data, but new it just write it in one continuous line to prevent this I added bw.newLine(); just before the write..

Idan Zimbler
Guest
Idan Zimbler

thank you very much!
it worked.

kabir
Guest
kabir

Thanks a lot for your easy to understand guide.

Jystinz
Guest
Jystinz

how to set permission file

Sailendra Narayan Jena
Guest
Sailendra Narayan Jena

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

Batoor
Guest
Batoor

for which purpose we use file.getAbsoluteFile?

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

rishi
Guest
rishi

thanxx Mkyong :) its really helpful…

heinrich
Guest
heinrich

thanks sir mkyong. you help me a lot.

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?

minerguy31
Guest
minerguy31

You can’t write directly to a .doc like that

A's
Guest
A's

Thnaks!!!

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 »

Jens Preem
Guest
Jens Preem

Am I in a right direction when I am looking at this example?
http://sfdv3006.wikidot.com/file-sort-filter

timmy
Guest
timmy

no

NG
Guest
NG

wooops not reader its writer lol

NG
Guest
NG

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

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

joe
Guest
joe

great help, always result number one when Googling :)

anupam ghosh
Guest
anupam ghosh

Hi Mkyong,

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

Regards
Anupam

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.

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 {

Al
Guest
Al

Two problems….

1. In the code that Mkyong shows, he never flushes. Before you close the Buffer, you should flush it. Otherwise, the Buffer may never write to disk (because it never fills up). Calling flush() will force the BufferedWriter to empty its contents.
2. Your code never calls close(). After you flush the BufferedWriter, close() it….

-Al

dmead
Guest
dmead

API says close() does a flush first

reza
Guest
reza

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

thanks a lot

best regards

Daniel
Guest
Daniel

You use BufferedWriter to write CHARACTERS from a buffer into a file.
FileOutputStream is used to write BYTES into a file directly, not using a buffer.

Hope it helped!

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(); } } }

t3ster
Guest
t3ster

This code will not work. This line “File file =new File(“C:/filename.txt”);” will not work.
Use “\\” instead of “/” in above line where you give the location of file.

Cod3r
Guest
Cod3r

C:\\…. is for a windows. This is how the path is typed into a windows.

/users/mkyong/….. is for a mac. This is how the path is typed into a mac.

TanViet
Guest
TanViet

You should use “C://filename.txt”. It works for me.

Cod3r
Guest
Cod3r

“C:\\filename.txt” is for Windows computers
/users/mkyoung is for Mac

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…

trackback
Java I/O Tutorials | J2EE Web Development Tutorials

[…] Write file with BufferedWriter […]

QuickSilver
Guest
QuickSilver

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

kishan
Guest
kishan

can anyone teach me java
:(