Menu
Topics Index
...
`

BufferedWriter - Java Example Program


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

class BufferedWriterExampleTest
{
    public static void main(String arg[])
    {
        String s = "Hello World!";
                char[] c = "ABCDEFGHIJKLMN".toCharArray();
                
                try {
                    StringWriter sw = new StringWriter();
                    BufferedWriter bw = new BufferedWriter(sw);
        
                    bw.write(s, 0, 5); // LINE B
                    bw.newLine(); // LINE C
                    bw.write(c, 8, 3); //LINE D
                    bw.flush(); // LINE E
                    System.out.println(sw.getBuffer());
                    bw.close(); // LINE F
                    bw.append(s); // ERROR OCCURS
                    
                } catch (Exception e) {
                    System.out.println("Stream is closed so you cant append.");
                }    
    }
}
OUTPUT

Hello
IJK
Stream is closed so you cant append.

DESCRIPTION

In this program, We have a string and a character array, at LINE B we are writing 5 characters of string, at LINE C a new line, 3 characters from position 9 of character array to buffer-writer. At LINE E flushing the whole buffer-writer to string writer and printing the written data. At LINE F the buffer-writer is closed and in next line trying to append the buffer-writer then exception occurs.

THINGS TO TRY
  • Try to execute these two programs in eclipse.
  • Try to create a new file and add data into in using all methods.
  • Try to create different files like pdf, doc etc.,

© meritcampus 2019

All Rights Reserved.

Open In App