Friday, July 19, 2013

BufferedReader vs. BufferedWriter

BufferedReader class wraps FileReader object to read text from a character-file in the efficient way (characters are buffered). By using the BufferedReader class, it is able to read each line of text from the character file.
BufferedWriter class has the reverse functionality. It provides efficient way to write text to the character-file. It is easy to write text with new lines.

BufferedReader constructor:
-BufferedReader(FileReader  fr)
Its useful method:
-readLine(): String

BufferedWriter constructor:
-BufferedWriter(FileWriter  fw)
Its useful method:
-newLine():void

In the example below, the writeText method is called to write the string "Hello, world!" to a text file called testfile1.txt. After creating a BufferedWriter object, you can use its write(String text) method to write text to the file. If you want a line break between parts of the text, you need to use the newLine method. To read the text from the file, the readText is called. You can use the FileReader class to read each character from the file. However, if you need to read the text one line at a time you have to construct a BufferedReader object. When constructing the BufferedReader object, you need to pass the FileReader object.

public class Example{

public static void main(String[] args){
writeText("Hello, world!","testfile1.txt");
readText("testfile1.txt");
}
public static void writeText(String text,String desc) throws IOException{

FileWriter fw=new FileWriter(desc); //create file writer
BufferedWriter bw=new BufferedWriter(fw); //create buffering writer
bw.write(text); //write text to the file
bw.newLine(); //write new line
bw.write("text after the new line...");
bw.flush();
bw.close();

}
public static void readText(String src) throws IOException{

FileReader fr=new FileReader(src); //create file reader
BufferedReader br=new BufferedReader(fr); //create buffering reader
String text="";
while((text=br.readLine())!=null){ //read each line from the file
System.out.println(text);
}
br.close();

}

}

No comments:

Post a Comment