Java BufferedWriter.close()

Syntax

BufferedWriter.close() has the following syntax.

public void close()  throws IOException

Example

In the following code shows how to use BufferedWriter.close() method.


// www .j av  a  2 s.c om

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;

public class Main {
  public static void main(String[] args) throws IOException {

    StringWriter sw = new StringWriter();

    BufferedWriter bw = new BufferedWriter(sw);

    bw.append("java2s.com");

    bw.close();

    System.out.println(sw.getBuffer());

    // appending after closing will throw error
    bw.append("2");

    System.out.println(sw.getBuffer());

  }
}

The code above generates the following result.