Java IO Tutorial

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 Author

author image
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

Subscribe
Notify of
39 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Brutus
7 years ago

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

San
4 years ago
Reply to  mkyong
mohamed
8 years ago

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
8 years ago

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);
bw.write(drive);
bw.close();

System.out.println("Done: " + drive);

} catch (IOException e) {
e.printStackTrace();
}

Christian Munch Hammervig
8 years ago

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
8 years ago

thank you very much!
it worked.

Wasim Memon
10 years ago

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

kabir
5 years ago

Thanks a lot for your easy to understand guide.

Jystinz
5 years ago

how to set permission file

Sailendra Narayan Jena
5 years ago

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

Batoor
8 years ago

for which purpose we use file.getAbsoluteFile?

rishi
10 years ago

thanxx Mkyong 🙂 its really helpful…

heinrich
10 years ago

thanks sir mkyong. you help me a lot.

Alexandra
10 years ago

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
8 years ago
Reply to  Alexandra

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

A's
10 years ago

Thnaks!!!

Jens Preem
10 years ago

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 line in standard output. I see a class here writes a file.
What I would like to construct myself would be a scheme of three classes.
A to read lines and feed them forward B do stuff on lines and feed them forward C append lines to file. So I dont have to embed the do stuff-and write stuff out parts in the Reading class. (frex. into BufferedReaderExample while loop)
So that I could replace the B class/object any time I want.
Have you any pointers how to set up this system – how should my A and B look like.
When I want seamless line by line editing, and yet don’t want to always embed my editing paert into my reader part.
Do I then have to call my A n-times so it’ll return string n-times, and feed it to the B.
N-being the number of lines in text file. It seems that in such case some internal counter should be needed – also it means the class A should make sure how many lines there are in text file – which would mean an additional read-through. Which would be a waste of time.
Have you encountered such set-up or can show pointers etc. I would like to use the modularity without losing the speed or getting too hackish.

timmy
10 years ago
Reply to  Jens Preem

no

Jens Preem
10 years ago
Reply to  Jens Preem

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

NG
10 years ago

wooops not reader its writer lol

NG
10 years ago

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

sankar
10 years ago

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
10 years ago

great help, always result number one when Googling 🙂

anupam ghosh
10 years ago

Hi Mkyong,

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

Regards
Anupam

Jayanth
11 years ago

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

Philip
11 years ago

… 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
11 years ago
Reply to  Philip

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
9 years ago
Reply to  Al

API says close() does a flush first

reza
11 years ago

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

thanks a lot

best regards

Daniel
11 years ago
Reply to  reza

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
11 years ago

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();
    	}
    }
}
TanViet
10 years ago
Reply to  Faisal

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

Cod3r
10 years ago
Reply to  TanViet

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

t3ster
11 years ago
Reply to  Faisal

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
10 years ago
Reply to  t3ster

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.

Paul
11 years ago

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…

QuickSilver
9 years ago

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

kishan
10 years ago

can anyone teach me java
🙁