How to write to file in Java – BufferedWriter

In Java, BufferedWriter is a character streams class to handle the character data. Unlike bytes stream (convert data into bytes), you can just write the strings, arrays or characters data directly to file.

package com.mkyong;
 
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) {
		try {
 
			String content = "This is the content to write into file";
 
			File file = new File("/users/mkyong/filename.txt");
 
			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}
 
			FileWriter fw = new FileWriter(file.getAbsoluteFile());
			BufferedWriter bw = new BufferedWriter(fw);
			bw.write(content);
			bw.close();
 
			System.out.println("Done");
 
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

Reference

  1. BufferedWriter documentation
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.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

  • Pingback: electricians mobile al()

  • Pingback: craftsman electrician pouch()

  • Pingback: house blue()

  • Pingback: b pumper reality show()

  • Pingback: f mcgovern locksmiths()

  • Pingback: locksmiths mobile al()

  • Pingback: electrician union los angeles()

  • Pingback: home page()

  • Pingback: bottled alkaline water()

  • Pingback: water ionizer pay plan loans()

  • Pingback: parking()

  • Pingback: water ionizer()

  • Pingback: sms laan nu()

  • Pingback: mp4 mobile porn()

  • Pingback: stop parking()

  • Pingback: lan penge online nu()

  • Pingback: lan nu og her()

  • Pingback: TVPackages.net()

  • Pingback: DIRECTV vs Dish()

  • Pingback: online casinos()

  • Pingback: best online casinos()

  • Pingback: How to Unblock Viber in UAE Dubai()

  • Pingback: kangen water()

  • Pingback: kangen water()

  • Pingback: water ionizer()

  • Pingback: water ionizers()

  • Pingback: tv online, online tv()

  • Pingback: streaming movies()

  • Pingback: Learn More()

  • Pingback: Blue Coaster33()

  • heinrich

    thanks sir mkyong. you help me a lot.

  • 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?

  • A’s

    Thnaks!!!

  • 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 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.

  • http://yahoo NG

    wooops not reader its writer lol

  • http://yahoo NG

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

  • 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

  • http://non joe

    great help, always result number one when Googling :)

  • anupam ghosh

    Hi Mkyong,

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

    Regards
    Anupam

  • kishan

    can anyone teach me java
    :(

  • 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

    … 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 {

    • http://monsterpixelgames.com 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

  • reza

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

    thanks a lot

    best regards

    • 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!

  • http://faisalnet5.blogspot.com/ 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 = &quot;This is the content to write into file&quot;;
     
        	    File file =new File(&quot;C:/filename.txt&quot;);
     
        	    //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(&quot;Done&quot;);
     
        	}catch(IOException e){
        		e.printStackTrace();
        	}
        }
    }
    • 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

        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.

    • http://tanvietblog.com TanViet

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

      • Cod3r

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

  • 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…

  • Pingback: Java I/O Tutorials | J2EE Web Development Tutorials()