BufferedWriter

A BufferedWriter is a Writer that buffers ouput.

A BufferedWriter has these two constructors:

BufferedWriter(Writer outputStream)
creates a buffered stream using a buffer with a default size.
BufferedWriter(Writer outputStream, int bufSize)
the size of the buffer is passed in bufSize.
void close()
Closes the stream, flushing it first.
void flush()
Flushes the stream.
void newLine()
Writes a line separator.
void write(char[] cbuf, int off, int len)
Writes a portion of an array of characters.
void write(int c)
Writes a single character.
void write(String s, int off, int len)
Writes a portion of a String.

Revised from Open JDK source code


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;

public class Main {
  public static void main(String[] args) throws Exception {
    BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
    System.out.println(stdin.readLine());
    BufferedReader in = new BufferedReader(new FileReader("Main.java"));
    String s, s2 = new String();
    while ((s = in.readLine()) != null)
      s2 += s + "\n";
    in.close();
    StringReader in1 = new StringReader(s2);
    int c;
    while ((c = in1.read()) != -1)
      System.out.print((char) c);
    BufferedReader in2 = new BufferedReader(new StringReader(s2));
    PrintWriter out1 = new PrintWriter(new BufferedWriter(new FileWriter(
        "IODemo.out")));
    int lineCount = 1;
    while ((s = in2.readLine()) != null)
      out1.println(lineCount++ + ": " + s);
    out1.close();
  }
}

Create BufferedWriter from standard System.out


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Main {
  public static void main(String[] args) throws Exception {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String strLine = in.readLine();
    BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
    out.write(strLine, 0, strLine.length());
    out.flush();
    in.close();
    out.close();
  }
}

Write String to a file with BufferedWriter


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;

public class Main {
  public static void main(String[] args) throws Exception {
    Writer writer = null;

    String text = "This is a text file";

    File file = new File("write.txt");
    writer = new BufferedWriter(new FileWriter(file));
    writer.write(text);
    writer.close();

  }
}
Home 
  Java Book 
    File Stream  

BufferedWriter:
  1. BufferedWriter
  2. BufferedWriter: close()
  3. BufferedWriter: flush()
  4. BufferedWriter: write(String str)
  5. BufferedWriter: write(String s, int off, int len)