Buffer or Not
Not so long ago I decided to try to pick up Java again, and I don’t mean trying to pick up the city of Java. I mean the hybrid programming…
Buffer or Not
Not so long ago I decided to try to pick up Java again, and I don’t mean trying to pick up the city of Java. I mean the hybrid programming language spawned by Sun Microsystems.
For a couple of months now I have been off and on java video tutorials, but I’m in this group right not and we have this really awesome tutor and all.
The prior elusive language is not so elusive anymore.
I just wanted to share something I learnt today….
import java.io.*;
public class FileRead{
public static void main(String args[])throws IOException{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
fr.close();
} }The above code make use of the inbuilt Java IO library to handle reading and writing files.
But where i wanna really highlight is the existence of another library that builds ontop of either the reader or writer classes to perform the same operation.
And this Class is the BufferedReader and BufferedWriter Classes.
example:
FIileWriter
FileWriter fw = new FileWriter(“out.txt”); fw.write(“simple method”); fw.close();
BufferedWriter
FileWriter fw = new FileWriter(“out.txt”); BufferedWriter bw = new BufferedWriter(fw); bw.write(“too much code”); bw.close();
The above code is almost same for the FileReader class, the bufferedReader just wraps around the FileReader class.
While FileReader class helps in writing on file but its efficiency is low since it has to retrieve one character at a time from file but BufferedReader takes chunks of data and store it in buffer so instead of retrieving one character at a time from file retrieval becomes easy using buffer.
The BufferedReader reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines.
Java’s pretty cool ):