The Wayback Machine - https://web.archive.org/web/20240708014353/https://www.geeksforgeeks.org/character-stream-vs-byte-stream-java/
Open In App

Character Stream Vs Byte Stream in Java

Last Updated : 09 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

A stream is a sequence of data. I/O Stream refers to a stream that is unlikely 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.

  • Input Stream: reads data from the source. 
  • Output Stream: writes data to a 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. 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.

Key points while using and dealing with any of the above streams are as follows: 

  1. Names of character streams typically end with Reader/Writer and names of byte streams end with InputStream/OutputStream
  2. 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.
  3. 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.
  4. The above codes may not run in online compilers as files may not exist.

Character Stream

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.

Character Stream

Example

Java




// Java Program illustrate Reading
// a File in Human Readable
// Format Using FileReader Class
 
// Importing required classes
import java.io.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
 
        // Initially assigning null as we have not read
        // anything
        FileReader sourceStream = null;
 
        // Try block to check for exceptions
        try {
 
            // Reading from file
            sourceStream = new FileReader(
                "/Users/mayanksolanki/Desktop/demo.rtf");
 
            // Reading sourcefile and writing content to
            // target file character by character.
 
            int temp;
 
            // If there is content inside file
            // than read
            while ((temp = sourceStream.read()) != -1)
                System.out.println((char)temp);
           
          // Display message for successful execution of program
          System.out.print("Program successfully executed");
        }
 
        // finally block that executes for sure
        // where we are closing file connections
        // to avoid memory leakage
        finally {
 
            // Closing stream as no longer in use
            if (sourceStream != null)
                sourceStream.close();
        }
    }
}


Output: Writes content to the target file character by character

Program successfully executed

Byte Stream

Byte streams process data byte by byte (8 bits). For example, FileInputStream is used to read from the source and FileOutputStream to write to the destination.

Example:

Java




// Java Program Illustrate ByteStream Class to
// Copy Contents of One File to Another File
 
// Importing required classes
import java.io.*;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
        throws IOException
    {
 
        // Initially assigning null ot objects for
        // reading and writing to file
        FileInputStream sourceStream = null;
        FileOutputStream targetStream = null;
 
        // Try block to check for exceptions
        try {
 
            // Passing the files via local directory
            sourceStream = new FileInputStream(
                "/Users/mayanksolanki/Desktop/demo.rtf");
            targetStream = new FileOutputStream(
                "/Users/mayanksolanki/Desktop/democopy.rtf");
 
            // Reading source file and writing content to
            // target file byte by byte
            int temp;
 
            // If there is content inside file
            // than read
            while ((temp = sourceStream.read()) != -1)
                targetStream.write((byte)temp);
           
          // Display message for successful execution of program
          System.out.print("Program successfully executed");
        }
 
        // finally block that executes for sure
        // where we are closing file connections
        // to avoid memory leakage
        finally {
 
            if (sourceStream != null)
                sourceStream.close();
 
            if (targetStream != null)
                targetStream.close();
        }
    }
}


Output:

Program successfully executed



Similar Reads

Java Guava | Bytes.indexOf(byte[] array, byte target) method with Examples
Bytes.indexOf(byte[] array, byte target) method of Guava's Bytes Class accepts two parameters array and target. If the target exists within the array, the method returns the position of its first occurrence. If the target does not exist within the array, the method returns -1. Syntax: public static int indexOf(byte[] array, byte target) Parameters:
3 min read
Java Guava | Bytes.indexOf(byte[] array, byte[] target) method with Examples
Bytes.indexOf(byte[] array, byte[] target) method of Guava's Bytes Class accepts two parameters array and target. If the target exists within the array, the method returns the start position of its first occurrence. If the target does not exist within the array, the method returns -1. Syntax: public static int indexOf(byte[] array, byte[] target) P
3 min read
Difference between Stream.of() and Arrays.stream() method in Java
Arrays.stream() The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source. Example: Java Code // Java program to demonstrate Arrays.stream() method import java.uti
5 min read
Java.Lang.Byte class in Java
In Java, Byte class is a wrapper class for the primitive type byte which contains several methods to effectively deal with a byte value like converting it to a string representation, and vice-versa. An object of the Byte class can hold a single byte value. Constructors of Byte Class There are mainly two constructors to initialize a Byte object- 1.
6 min read
Count occurrence of a given character in a string using Stream API in Java
Given a string and a character, the task is to make a function which counts the occurrence of the given character in the string using Stream API. Examples: Input: str = "geeksforgeeks", c = 'e' Output: 4 'e' appears four times in str. Input: str = "abccdefgaa", c = 'a' Output: 3 'a' appears three times in str. Approach: Convert the string into char
1 min read
foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
Byte toString() method in Java with examples
The toString() method of Byte class is a built in method in Java which is used to return a String value. public String toString() Syntax: ByteObject.toString() Return Value: It returns a String object, the value of which is equal to the value of the ByteObject. Below is the implementation of toString() method: Java Code // Java code to implement //
2 min read
Byte floatValue() method in Java with examples
The floatValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as float. Syntax ByteObject.floatValue() Return Value: It return the value of ByteObject as float. Below is the implementation of floatValue() method in Java: Example 1: // Java code to demonstrate // Byte floatValue() method cla
2 min read
Byte intValue() method in Java with examples
The intValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as int. Syntax ByteObject.intValue() Return Value: It returns the value of ByteObject as int. Below is the implementation of intValue() method in Java: Example 1: // Java code to demonstrate // Byte intValue() method class GFG { pu
2 min read
Byte doubleValue() method in Java with examples
The doubleValue() method of Byte class is a built in method in Java which is used to return the value of this Byte object as double. Syntax ByteObject.doubleValue() Return type: It returns the value of ByteObject as double. Below is the implementation of doubleValue() method in Java: Example 1: // Java code to demonstrate // Byte doubleValue() meth
2 min read
Practice Tags :
three90RightbarBannerImg