How to write to file in Java – BufferedWriter

In Java, you can use java.io.BufferedWriter to write content to a file.

Note
The BufferedWriter is a character stream class to handle the character data. Unlike byte stream (convert data into bytes), you can just write the strings, arrays or character data directly to a file.

1. Classic BufferedWriter

A classic BufferedWriter example to write content to a file, create the file if doesn’t exist, the existing content will be overridden.

WriteToFileExample1.java

package com.mkyong;

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

public class WriteToFileExample1 {

	private static final String FILENAME = "E:\\test\\filename.txt";

	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(FILENAME);
			bw = new BufferedWriter(fw);
			bw.write(content);

			System.out.println("Done");

		} catch (IOException e) {

			e.printStackTrace();

		} finally {

			try {

				if (bw != null)
					bw.close();

				if (fw != null)
					fw.close();

			} catch (IOException ex) {

				ex.printStackTrace();

			}

		}

	}

}

Output : A new file is created with the following content :

E:\\test\\filename.txt

This is the content to write into file

2. JDK7 Example

try-with-resources example to auto close the file writer.

WriteToFileExample2.java

package com.mkyong;

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

public class WriteToFileExample2 {

	private static final String FILENAME = "E:\\test\\filename.txt";

	public static void main(String[] args) {

		try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME))) {

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

			bw.write(content);
			
			// no need to close it.
			//bw.close();

			System.out.println("Done");

		} catch (IOException e) {

			e.printStackTrace();

		}

	}

}

3. BufferedWriter – Append

To append content to the end of a file, pass a true to FileWriter


	// append to end of file
	FileWriter fw = new FileWriter(FILENAME, true);
	BufferedWriter bw = new BufferedWriter(fw);

References

  1. The try-with-resources Statement
  2. How to append content to file in Java
  3. BufferedWriter JavaDoc

About the Author

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

Comments

avatar
26 Comment threads
12 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
33 Comment authors
kabirJystinzSailendra Narayan JenaBrutusIdan Zimbler 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.

heinrich
Guest
heinrich

thanks sir mkyong. you help me a lot.

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

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.

rishi
Guest
rishi

thanxx Mkyong :) its really helpful…

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

kishan
Guest
kishan

can anyone teach me java
:(

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.