dsa

Java BufferedWriter

In this tutorial, we will learn about the Java BufferedWriter, its constructors and its methods with the help of an example.

Java BufferedWriter writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings.

Constructors of BufferedWriter

  • BufferedWriter(Writer out) :Creates a buffered character-output stream that uses a default-sized output buffer.
  • BufferedWriter(Writer out, int sz) :Creates a new buffered character-output stream that uses an output buffer of the given size.

Methods

MethodsDescription
void close()Closes the stream, flushing it first.
void flush()Flushes the stream.
void newLine()Writes a line separator.
boolean markSupported()Tells whether this stream supports the mark() operation, which it does.
void write(int c)Writes a single character.
void write(char[] cbuf, int off, int len)Writes a portion of an array of characters.
void write(String s, int off, int len)Writes a portion of a String.

Examples :


import java.io.FileWriter;
import java.io.BufferedWriter;

public class Codemistic 
{

  	public static void main(String args[]) 
	{

    		String data = "This file consists of a single line.";

    		try 
		{
      			// Creates a FileWriter
      			FileWriter file = new FileWriter("output.txt");

      			// Creates a BufferedWriter
      			BufferedWriter output = new BufferedWriter(file);

      			// Writes the string to the file
      			output.write(data);

      			// Closes the writer
      			output.close();
    		}
    		catch (Exception e) 
		{
      			e.getStackTrace();
    		}
  	}
}


Output :

A file named output.txt will be created which will contain the below line:
This file consists of a single line.