Reputation: 135
I'm trying to create a program that allows me to get names from a local file and add them to a String array of names. I don't completely understand the difference between character streams, binary streams, and buffer streams, and looking online didn't answer my question, which is: which type of stream would I use to read from a text file in order to create a String array?
Upvotes: 0
Views: 831
Reputation: 21981
The difference is simple. According to this tutorial
- Byte Streams handle I/O of raw binary data.
- Character Streams handle I/O of character data, automatically handling translation to and from the local character set.
- Buffered Streams optimize input and output by reducing the number of calls to the native API.
Upvotes: 1
Reputation: 1503669
I don't completely understand the difference between character streams, binary streams, and buffer streams
Buffers are a red herring here - that's just an implementation detail, usually to make things more efficient. It's important to understand whether you're reading binary data or text data. If you're reading a text file, you want a Reader
of some description. Your file contains binary data (all files are basically bytes) and you need to say how to convert that to text. You could use a FileReader
, but I'd prefer to use a FileInputStream
wrapped in an InputStreamReader
, as then you can specify the encoding to convert between binary and text. You'll need to know the encoding of your file, e.g. UTF-8.
Any InputStream
returns just binary data; and Reader
returns textual data.
Either way, if you want to read line by line (it's unclear what your array would consist of) you'll want a BufferedReader
to wrap your InputStreamReader
or FileReader
, as that provides a readLine()
method.
Hmmm then why would people ever use byte streams, if we all use characters.
We don't. Image files, music, video, compressed data, encrypted data etc aren't inherently textual data. If you read an image file with a Reader
, you're almost bound to lose some data.
Think of text as just another file format - if you were trying to load an image to display it, you'd need something which understood that image file format; if you were trying to load a music file to play it, you'd need something which understood that audio file format - with text, an InputStreamReader
understands text.
Even though in all cases we've got bytes at the file level, the class you use determines how those bytes are interpreted.
Upvotes: 3