Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - stream of bytes vs. stream of characters?

Title is pretty self-explanatory. In a lot of the JRE javadocs I see the phrases "stream of bytes" and "stream of characters" all over the place.

But aren't they the same thing? Or are they slightly different (e.g. interpreted differently) in Java-land? Thanks in advance.

like image 958
IAmYourFaja Avatar asked Feb 26 '13 20:02

IAmYourFaja


People also ask

What is difference between byte and character?

Byte Streams − These handle data in bytes (8 bits) i.e., the byte stream classes read/write data of 8 bits. Using these you can store characters, videos, audios, images etc. Character Streams − These handle data in 16 bit Unicode. Using these you can read and write text data only.

Why does Java define both byte and character stream?

Modern versions of Java define two types of streams: byte and character. (The original version of Java defined only the byte stream, but character streams were quickly added.) Byte streams provide a convenient means for handling input and output of bytes. They are used, for example, when reading or writing binary data.

What is the advantage of having character stream in Java?

In Java, characters are stored using Unicode conventions. Character stream automatically allows us to read/write data character by character. For example, FileReader and FileWriter are character streams used to read from the source and write to the destination.


1 Answers

In Java, a byte is not the same thing as a char. Therefore a byte stream is different from a character stream. Bytes are intended for arbitrary binary data; characters are specifically for data representing the building blocks of strings.

but if a char is only 1 byte in width

Except that it's not. As per the JLS §4.2.1 a char is a number in the range:

from '\u0000' to '\uffff' inclusive, that is, from 0 to 65535

But a byte is a number in the range

from -128 to 127, inclusive

like image 129
Matt Ball Avatar answered Oct 21 '22 22:10

Matt Ball