As I tentatively understand it at the moment:
DataInputStream is an InputStream subclass, hence it reads and writes bytes. If you are reading bytes and you know they are all going to be ints or some other primitive data type, then you can read those bytes directly into the primitive using DataInputStream.
- Question: Would you would need to know the type (int, string, etc) of the content being read before it is read? And would the whole file need to consist of that one primitive type?
The question I am having is: Why not use an InputStreamReader wrapped around the InputStream's byte data? With this approach you are still reading the bytes, then converting them to integers that represent characters. Which integers represent which characters depends on the character set specified, e.g., "UTF-8".
- Question: In what case would an
InputStreamReaderfail to work where aDataInputStreamwould work?
My guess answer: If speed is really important, and you can do it, then converting the InputStream's byte data directly to the primitive via DataInputStream would be the way to go? This avoids the Reader having to "cast" the byte data to an int first; and it wouldn't rely on providing a character set to interpret which character is being represented by the returned integer. I suppose this is what people mean by DataInputStream allows for a machine-indepent read of the underlying data.
- Simplification:
DataInputStreamcan convert bytes directly to primitives.
Question that spurred the whole thing: I was reading the following tutorial code:
FileInputStream fis = openFileInput("myFileText");
BufferedReader reader = new BufferedReader( new InputStreamReader( new DataInputStream(fis)));
EditText editText = (EditText)findViewById(R.id.edit_text);
String line;
while( (line = reader.readline()) != null){
editText.append(line);
editText.append("\n");
}
...I do not understand why the instructor chose to use new DataInputStream(fis) because it doesn't look like any of the ability to directly convert from bytes to primitives is being leveraged?
- Am I missing something?
Thanks for your insights.