Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use DataInputStream or BufferedInputStream

Tags:

java

io

I want to read each line from a text file and store them in an ArrayList (each line being one entry in the ArrayList).

So far I understand that a BufferedInputStream writes to the buffer and only does another read once the buffer is empty which minimises or at least reduces the amount of operating system operations.

Am I correct - do I make sense?

If the above is the case in what situations would anyone want to use DataInputStream. And finally which of the two should I be using and why - or does it not matter.

like image 357
Ankur Avatar asked Apr 10 '09 11:04

Ankur


People also ask

What is the difference between DataInputStream and BufferedInputStream in Java?

DataInputStream is a kind of InputStream to read data directly as primitive data types. BufferedInputStream is a kind of inputStream that reads data from a stream and uses a buffer to optimize speed access to data. data is basicaly read ahead of time and this reduces disk or network access.

Is DataInputStream deprecated?

DataInputStream has been deprecated because it does not properly convert bytes to characters. The alternative shown here will not work for all programs.

Why is BufferedInputStream faster?

With a BufferedInputStream , the method delegates to an overloaded read() method that reads 8192 amount of bytes and buffers them until they are needed. It still returns only the single byte (but keeps the others in reserve). This way the BufferedInputStream makes less native calls to the OS to read from the file.

Why do we use DataInputStream?

Class DataInputStream. A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.


1 Answers

Use a normal InputStream (e.g. FileInputStream) wrapped in an InputStreamReader and then wrapped in a BufferedReader - then call readLine on the BufferedReader.

DataInputStream is good for reading primitives, length-prefixed strings etc.

like image 109
Jon Skeet Avatar answered Sep 28 '22 22:09

Jon Skeet