Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need for Data Input Stream

What is the difference between

FileInputStream fstream = new FileInputStream ("file1.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));

and

FileInputStream fstream = new FileInputStream ("file1.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

Do we really need a DataInputStream here?

like image 979
Arun A K Avatar asked Jul 17 '12 05:07

Arun A K


2 Answers

The use of DataInputStream is a common mistake which I believe comes from copy-and-paste from different pieces of code. You want to read the files as either text e.g. BufferedReader OR binary e.g. DataInputStream. Its highly unlikely you want to use both and trying to is likely to lead to confusion.

For Text which is buffered

BufferedReader br = new BufferedReader(new FileReader(file));

For binary which is buffered

DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
like image 194
Peter Lawrey Avatar answered Sep 20 '22 22:09

Peter Lawrey


The significant thing about the object passed to the InputStreamReader() constructor is that it will be the object that will bear the weight of any synchronization holds. If you don't want your FileInputStream to potentially be held up by many calls to it, then the second option is the way to go. See the source of Reader.

like image 29
gobernador Avatar answered Sep 23 '22 22:09

gobernador