Java BufferedWriter class is a part of package.

Java BufferedWriter

Java BufferedWriter Usage Flow


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.

    Output of the above program is below:


    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.

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

    Let’s have look at the below example program.

  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 writtenoff: 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.


  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 arrayoff : 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.

  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.


  5. flush(): This method flushes the stream and write the buffer to the output file.

  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.

    Above program will throw following exception.

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

By admin

Leave a Reply

%d bloggers like this: