A stream is a method to sequentially access a file. I/O Stream means an input source or output destination representing different types of sources e.g. disk files.The java.io package provides classes that allow you to convert between Unicode character streams and byte streams of non-Unicode text.
Stream – A sequence of data.
Input Stream: reads data from source.
Output Stream: writes data to destination.
In Java, characters are stored using Unicode conventions (Refer this for details). Character stream automatically allows us to read/write data character by character. For example FileReader and FileWriter are character streams used to read from source and write to destination.
Shows contents of file test.txt
Byte streams process data byte by byte (8 bits). For example FileInputStream is used to read from source and FileOutputStream to write to the destination.
When to use Character Stream over Byte Stream?
- In Java, characters are stored using Unicode conventions. Character stream is useful when we want to process text files. These text files can be processed character by character. A character size is typically 16 bits.
When to use Byte Stream over Character Stream?
- Byte oriented reads byte by byte. A byte stream is suitable for processing raw data like binary files.
- Names of character streams typically end with Reader/Writer and names of byte streams end with InputStream/OutputStream
- The streams used in example codes are unbuffered streams and less efficient. We typically use them with buffered readers/writers for efficiency. We will soon be discussing use BufferedReader/BufferedWriter (for character stream) and BufferedInputStream/BufferedOutputStream (for byte stream) classes.
- It is always recommended to close the stream if it is no longer in use. This ensures that the streams won’t be affected if any error occurs.
- The above codes may not run in online compilers as files may not exist.
This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Difference between Stream.of() and Arrays.stream() method in Java
- Count occurrence of a given character in a string using Stream API in Java
- Stream In Java
- Java 8 Stream
- How to get ArrayList from Stream in Java 8
- Stream map() in Java with examples
- Stream.of(T t) in Java with examples
- Convert a Set to Stream in Java
- Array to Stream in Java
- Stream of() method in Java
- How to get Slice of a Stream in Java
- Stream.distinct() in Java
- Stream.concat() in Java
- Convert Stream to Set in Java
- Stream sorted() in Java