Character Stream Vs Byte Stream in Java
A stream in Java is a mechanism for sequentially accessing data from various sources, such as files, arrays, devices, and programs. While streams allow data processing on a per-item basis, they do not support bulk operations. It is essential to distinguish between byte streams and character streams since Java treats bytes and characters differently. Consequently, Java defines two types of streams: Byte Streams, primarily for binary data, and Character Streams, designed specifically for textual data processing, ensuring efficient and accurate handling of diverse data types in the language.
A byte stream facilitates file access on a byte-by-byte basis and is commonly used for input and output operations involving 8-bit bytes. While byte streams are versatile and suitable for various file types, they may not be ideal for handling text files efficiently, especially if they use Unicode encoding, where characters are represented by two bytes. In such cases, manual conversion becomes necessary. It is important to note that byte-oriented streams do not employ any specific encoding scheme, whereas character-oriented streams adopt UNICODE encoding for seamless handling of textual data. Additionally, all byte stream classes in Java are derived from the InputStream and OutputStream classes, forming the foundation of byte stream handling in the language.Example
When to use:
Byte streams should only be used for the most primitive I/O
When not to use:
You should not use Byte stream to read Character streams
e.g. To read a text file
A character stream operates by reading a file character by character. Character streams are considered higher-level compared to byte streams, as they encompass byte streams wrapped with additional logic to enable output of characters based on a specific encoding. Thus, for proper functionality, a character stream requires knowledge of the file's encoding. Character streams are versatile and capable of handling various character sets, including ASCII, Unicode, UTF-8, UTF-16, and more. All character stream classes in Java are derived from the Reader and Writer classes, forming the foundation of character stream handling in the language.Example
When to use:
To read character streams either from Socket or File of characters
- Character oriented are tied to datatype. Only string type or character type can be read through it while byte oriented are not tied to any datatype, data of any datatype can be read(except string) just you have to specify it.
- Character oriented reads character by character while byte oriented reads byte by byte.
- Character oriented streams use character encoding scheme(UNICODE) while byte oriented do not use any encoding scheme.
- Character oriented streams are also known as reader and writer streams Byte oriented streams are known as data streams-Data input stream and Data output stream.