Java BufferedWriter class is a part of java.io package.
Java BufferedWriter
Java BufferedWriter Usage Flow
Java BufferedWriter Constructors
BufferedWriter(Writer out)
: Creates a buffered character-output stream that uses a default sized output buffer with specified Writer object.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.
write(int c)
: This method writes a single character specified by int c.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354package 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 existsif (!file.exists()) {file.createNewFile();}// initialize BufferedWriterwriter = new BufferedWriter(fileWriter);//write integerswriter.write(50);writer.write(51);writer.write(52);System.out.println("File written successfully.");} catch (Exception e) {e.printStackTrace();} finally {// close BufferedWriterif (writer != null) {try {writer.close();} catch (IOException e) {e.printStackTrace();}}// close FileWriterif (fileWriter != null) {try {fileWriter.close();} catch (IOException e) {e.printStackTrace();}}}}}
Output of the above program is below:
1234File written successfully.<img class="alignnone wp-image-30384 size-full" src="https://all-learning.com/wp-content/uploads/2018/04/java-BufferedWriter-example1.png" alt="java-BufferedWriter-example" width="1200" height="628" />
If you noticed the program and the output file image, you might see that
writer.write(50);
is outputting as2
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.1234char c = 50;System.out.println(c); //prints 2BufferedWriter implements AutoCloseable interface, hence we can use try with resource while using BufferedWriter class.
Let’s have look at the below example program.
123456789101112131415161718192021222324252627282930package 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 existsif (!file.exists()) {file.createNewFile();}// write integerswriter.write(50);writer.write(51);writer.write(52);System.out.println("File written successfully.");} catch (Exception e) {e.printStackTrace();}}}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 writtenoff: Offset from which to start reading characterslen: Number of characters to be written
If the value of the
len
parameter is negative then no characters are written.123456789101112131415161718192021222324252627282930package 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 existsif (!file.exists()) {file.createNewFile();}// write stringwriter.write(data, 5, 11);System.out.println("File written successfully.");} catch (Exception e) {e.printStackTrace();}}}<img class="alignnone wp-image-30385 size-full" src="https://all-learning.com/wp-content/uploads/2018/04/java-BufferedWriter-write-examples.png" alt="java-BufferedWriter-write-example" width="1200" height="628" />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 arrayoff : Offset from which to start reading characterslen : 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.
1234567891011121314151617181920212223242526272829package 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 existsif (!file.exists()) {file.createNewFile();}// write char arraywriter.write(cbuf, 5, 11);System.out.println("File written successfully.");} catch (Exception e) {e.printStackTrace();}}}newLine()
: This method writes a line separator. The line separator string is defined by the system propertyline.separator
, and is not necessarily a single newline (‘n’) character.123456789101112131415161718192021222324252627282930313233package 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 existsif (!file.exists()) {file.createNewFile();}// write string with new linewriter.write(data, 0, 4);writer.newLine();writer.write(data, 5, 11);System.out.println("File written successfully.");} catch (Exception e) {e.printStackTrace();}}}<img class="alignnone wp-image-30386 size-full" src="https://all-learning.com/wp-content/uploads/2018/04/java-bufferedwriter-newlines.png" alt="java-bufferedwriter-newline" width="1200" height="628" />flush()
: This method flushes the stream and write the buffer to the output file.12345678910111213141516171819202122232425262728293031323334package 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 existsif (!file.exists()) {file.createNewFile();}// write stringwriter.write("Learn Java ");//flush the streamwriter.flush();// write stringwriter.write("with JournalDev.");//flush the streamwriter.flush();System.out.println("File written successfully.");} catch (Exception e) {e.printStackTrace();}}}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.1234567891011121314151617181920212223242526272829303132package 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 existsif (!file.exists()) {file.createNewFile();}// write stringwriter.write("Learn Java ");//close the streamwriter.close();// write stringwriter.write("with JournalDev.");System.out.println("File written successfully.");} catch (Exception e) {e.printStackTrace();}}}Above program will throw following exception.
1234567java.io.IOException: Stream closedat 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