BufferedWriter writes text to a character-output stream, to provide buffering for the efficient writing of single characters, arrays and strings.
- The buffer size may be specified, or the default size may be used.
BufferedWriter Constructors:
BufferedWriter Methods:
Java.io.BufferedWriter
class inherits methods from the following classes:
Example program which creates a file and writes some data into it.
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class TestA {
public static void main(String[] args) {
try {
String content = "This is the content to write into file.";
File file = new File("F:\\filename.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content); // LINE A
bw.close();
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
Done
Description:
It checks for the folder
filename.txt
in F drive if it is not found then creates a new
filename.txt
file and content will be written to the
txt
file and closes the
BufferWriter
.
Program for close, flush, newLine, write(char[] c, int from, int length), write(int c), write(String s, int from, int length)
.
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.");
}
}
}
OUTPUTHello
IJK
Stream is closed so you cant append.
DESCRIPTIONIn 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.,