Java BufferedWriter

Filed Under: Java

Java BufferedWriter class is a part of java.io package.

Java BufferedWriter

  • BufferedWriter is a sub class of java.io.Writer class.
  • BufferedWriter writes text to character output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.
  • The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
  • BufferedWriter is used to make lower-level classes like FileWriter more efficient and easier to use. Compared to FileWriters, BufferedWriters write relatively large chunks of data to a file at once, minimizing the number of times that slow, file-writing operations are performed.
  • The BufferedWriter class also provides a newLine() method to create platform-specific line separators automatically.
  • In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters.
     
    BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt")));
    

Java BufferedWriter Usage Flow

Java BufferedWriter

Java BufferedWriter Constructors

  1. BufferedWriter(Writer out): Creates a buffered character-output stream that uses a default sized output buffer with specified Writer object.
  2. BufferedWriter(Writer out, int sz) : Creates a buffered character-output stream that uses an output buffer of specified size with specified Writer object.

BufferedWriter Methods and Examples

Let’s have a look at the below methods of BufferedWriter class with examples.

  1. write(int c): This method writes a single character specified by int c.
    
    package com.journaldev.examples;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    import java.io.IOException;
    
    /**
     * Java write file using BufferedWriter write method
     * 
     * @author pankaj
     *
     */
    public class BufferedWriterWriteExample {
    
    	public static void main(String[] args) {
    		File file = null;
    		FileWriter fileWriter = null;
    		BufferedWriter writer = null;
    		try {
    			file = new File("D:/data/file.txt");
    			fileWriter = new FileWriter(file);
    			// create file if not exists
    			if (!file.exists()) {
    				file.createNewFile();
    			}
    			// initialize BufferedWriter
    			writer = new BufferedWriter(fileWriter);
    
    			//write integers
    			writer.write(50);
    			writer.write(51);
    			writer.write(52);
    			System.out.println("File written successfully.");
    		} catch (Exception e) {
    			e.printStackTrace();
    		} finally {
    			// close BufferedWriter
    			if (writer != null) {
    				try {
    					writer.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    			// close FileWriter
    			if (fileWriter != null) {
    				try {
    					fileWriter.close();
    				} catch (IOException e) {
    					e.printStackTrace();
    				}
    			}
    		}
    
    	}
    
    }
    

    Output of the above program is below:

    
    File written successfully.
    

    Java BufferedWriter Example

    If you noticed the program and the output file image, you might see that writer.write(50); is outputting as 2 in the file, it’s because the argument integer is converted to char and then written to file. Below code snippet output will clear your confusion.

    
    char c = 50;
    System.out.println(c); //prints 2
    

    BufferedWriter implements AutoCloseable interface, hence we can use try with resource while using BufferedWriter class.

    Let’s have look at the below example program.

    
    package com.journaldev.examples;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    
    /**
     * Java write file using BufferedWriter write method using try with resource
     * 
     * @author pankaj
     *
     */
    public class BufferedWriterWriteTryWithResource {
    
    	public static void main(String[] args) {
    		File file = new File("D:/data/file.txt");
    		try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
    			// create file if not exists
    			if (!file.exists()) {
    				file.createNewFile();
    			}
    			// write integers
    			writer.write(50);
    			writer.write(51);
    			writer.write(52);
    			System.out.println("File written successfully.");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    
    	}
    
    }
    
  2. write(String s, int off, int len): This method writes a portion of String s from int off to int len.

    s: String to be written

    off: Offset from which to start reading characters

    len: Number of characters to be written

    If the value of the len parameter is negative then no characters are written.

    
    package com.journaldev.examples;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    
    /**
     * Java write string into file using BufferedWriter write(String  s,  int  off,  int  len) method
     * 
     * @author pankaj
     *
     */
    public class BufferedWriterWriteString {
    
    	public static void main(String[] args) {
    		File file = new File("D:/data/file.txt");
    		String data = "This is BufferedWriter.";
    		try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
    			// create file if not exists
    			if (!file.exists()) {
    				file.createNewFile();
    			}
    			// write string
    			writer.write(data, 5, 11);
    			System.out.println("File written successfully.");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    
    	}
    
    }
    

    Java BufferedWriter write example

  3. write(char[] cbuf, int off, int len): This method writes a portion of an array of characters specified by char[] cbuf from int off to int len.

    cbuf : A character array

    off : Offset from which to start reading characters

    len : Number of characters to write

    This method stores characters from the given array into this stream’s buffer, flushing the buffer to the underlying stream as needed. If the requested length is at least as large as the buffer, however, then this method will flush the buffer and write the characters directly to the underlying stream. Thus, redundant BufferedWriters will not copy data unnecessarily.

    
    package com.journaldev.examples;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    
    /**
     * Java write string into file using BufferedWriter write(char[] cbuf,  int  off,  int  len) method
     * 
     * @author pankaj
     *
     */
    public class BufferedWriterWriteChar {
    
    	public static void main(String[] args) {
    		File file = new File("D:/data/file.txt");
    		char[] cbuf = "This is BufferedWriter.".toCharArray();
    		try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
    			// create file if not exists
    			if (!file.exists()) {
    				file.createNewFile();
    			}
    			// write char array
    			writer.write(cbuf, 5, 11);
    			System.out.println("File written successfully.");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    
    	}
    
    }
    
  4. newLine(): This method writes a line separator. The line separator string is defined by the system property line.separator, and is not necessarily a single newline (‘\n’) character.
    
    package com.journaldev.examples;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    
    /**
     * Java write string into file using 
     * BufferedWriter write(String  s,  int  off,  int  len) and newLine() method
     * 
     * @author pankaj
     *
     */
    public class BufferedWriterNewLineExample {
    
    	public static void main(String[] args) {
    		File file = new File("D:/data/file.txt");
    		String data = "This is BufferedWriter.";
    		try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
    			// create file if not exists
    			if (!file.exists()) {
    				file.createNewFile();
    			}
    			// write string with new line
    			writer.write(data, 0, 4);
    			writer.newLine();
    			writer.write(data, 5, 11);
    			System.out.println("File written successfully.");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    
    	}
    
    }
    

    Java BufferedWriter newline

  5. flush(): This method flushes the stream and write the buffer to the output file.
    
    package com.journaldev.examples;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    
    /**
     * Java BufferedWriter flush method example
     * 
     * @author pankaj
     *
     */
    public class BufferedWriterFlushExample {
    
    	public static void main(String[] args) {
    		File file = new File("D:/data/file.txt");
    		try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
    			// create file if not exists
    			if (!file.exists()) {
    				file.createNewFile();
    			}
    			// write string
    			writer.write("Learn Java ");
    			//flush the stream
    			writer.flush();
    			// write string
    			writer.write("with JournalDev.");
    			//flush the stream
    			writer.flush();
    			System.out.println("File written successfully.");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    
    	}
    
    }
    
  6. close(): This method flush the stream before close it. Once the stream has been closed, invocation of write() or flush() method will cause an IOException to be thrown. Closing a previously closed stream has no effect.
    
    package com.journaldev.examples;
    
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileWriter;
    
    /**
     * Java BufferedWriter close method example
     * 
     * @author pankaj
     *
     */
    public class BufferedWriterCloseExample {
    
    	public static void main(String[] args) {
    		File file = new File("D:/data/file.txt");
    		try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
    			// create file if not exists
    			if (!file.exists()) {
    				file.createNewFile();
    			}
    			// write string
    			writer.write("Learn Java ");
    			//close the stream
    			writer.close();
    			// write string
    			writer.write("with JournalDev.");
    			System.out.println("File written successfully.");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    
    	}
    
    }
    

    Above program will throw following exception.

    
    java.io.IOException: Stream closed
    	at java.io.BufferedWriter.ensureOpen(Unknown Source)
    	at java.io.BufferedWriter.write(Unknown Source)
    	at java.io.Writer.write(Unknown Source)
    	at com.journaldev.examples.BufferedWriterCloseExample.main(BufferedWriterCloseExample.java:27)
    

Also check java write file for more about how to write file in java.

That’s all for Java BufferedWriter, I hope nothing important got missed here.

Reference: Java Doc

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages