So far I've been using Scanner
s to read data from text files.
Example:
File file = new File("path\\to\\file") ;
Scanner scan = new Scanner(file) ;
System.out.println(scan.nextLine()) ;
And used FileWriter
s to write data into text files. Like this:
try
{
FileWriter writer = new FileWriter("Foo.txt") ;
writer.write("hello there!") ;
writer.close()
}
catch(IOException ex)
{
ex.printStackTrace() ;
}
A few days ago I was at a meeting with my instructor. When I was examining his code, I noticed that he had used a BufferedReader
and BufferedWriter
- a method of reading and writing to files that I have not used before. Then I asked him what's the difference between using a BufferedReader
and a Scanner
to read data from a file. He could not explain it to me.
So I did a bit of research and found out that the classes that lie under the hood to perform these operations are the InputStream
and OutputStream
. These classes have their respective subclasses like FileInputStream
, FileOutputStream
, etc.
Further into my research I came across the Reader
and Writer
classes which are used to read data from and write data to files. Again, like the InputStream
and OutputStream
, these classes are abstract
super
classes and have their own subclasses to perform read and write operations.
I'm not confused about this but...why? I mean, why are there different methods of doing the same thing? What's the significance? And which method is the most efficient way of dealing with file inputs and outputs?