Get free ebooK with 50 must do coding Question for Product Based Companies solved
Fill the details & get ebook over email
Thank You!
We have sent the Ebook on 50 Must Do Coding Questions for Product Based Companies Solved over your email. All the best!

Streams in Java

Last Updated on August 17, 2023 by Mayank Dham

Streams are a powerful feature introduced in Java 8 that revolutionized the way we work with collections and data manipulation. Streams provide a concise and functional way to perform operations on data, making code more readable, maintainable, and efficient. Whether you’re dealing with lists, arrays, or any collection, streams offer a modern approach to transform, filter, and process data. Let’s discuss what is stream in Java, and also types of streams in Java.

What are Streams in Java?

A java stream is a group of objects that can be piped together to produce the desired result.
Streams are used in Java to transfer data between programs and I/O devices like a file, network connections, or consoles.

What are the different Types of Streams in Java?

There are two types of java streams:

1. Byte Streams

ByteStream classes are used to read bytes from and write bytes to an input stream. To put it another way, ByteStream classes read and write 8-bit data. Using ByteStream classes, we can save video, audio, characters, and so on. The java.io package contains these classes.

Byte Java streams have a three-phase mechanism:

  • Split: A spliterator divides the input data source into a stream. The Java Spliterator interface is an internal iterator that divides the stream into smaller parts for traversal.
  • Apply: The elements in the stream are processed.
  • Combine: After the elements have been processed, they are combined once more to produce a single result.

The ByteStream classes are classified into two types: InputStream and OutputStream. These are the abstract super classes for all Input/Output stream classes.

  • InputStream:
    This type of java stream reads data from a source. An InputStream can read data from a file, network connection, or any other I/O device. An InputStream can be used to read data from a file

    Syntax of InputStream:

    FileInputStream sourceStream = new FileInputStream("path_to_file");
  • OutputStream:
    The outputstream is a java stream that takes data from a Java program and sends or writes it to the destination (data sink). A data flow out of a program is represented by an output. The output stream connects a Java program to a data sink. A Java program writes or sends data to the data sink.
    The data flow from a data source to a Java program via an input stream. The data flow from a Java program to a data sink via an output stream.

    Syntax of OutputStream:

    FileOutputStream targetStream = new FileOutputStream("path_to_file");

    Example of Byte Java Stream:
    Below we have the code implementation and explanation

    import java.io.*;   
    public class ByteStreamExample
    {
        public static void main(String[] args) throws IOException
        {
            FileInputStream sourceStream = null;
            FileOutputStream targetStream = null;
      
            try 
            {
                sourceStream = new FileInputStream("source.txt");
                targetStream = new FileOutputStream ("destination.txt");
      
                // Reading source file using read method 
                // and write to file byte by byte using write method
                int temp;
                while ((temp = sourceStream.read()) != -1)
                    targetStream.write((byte)temp);            
            }
            finally 
            {
                if (sourceStream != null){
                    sourceStream.close();   
                }
                if (targetStream != null){           
                    targetStream.close(); 
                }
            }
        }
    }
    

    Output:

    101000010001111111

    Explanation
    Let’s look at an example of using Byte Stream to copy the contents of one file to another. In this example, we’ll make two FileInputStream and FileOutputStream objects.
    The names of the source and destination files are passed to the FileInputStream and FileOutputStream classes as parameters. The content of the source file is then copied to the destination file. Here we are Assuming that we have already created a file called source.txt with the following contents, When we run the above program, it will create a destination.txt file in the same directory as the program file, with the same content as source.txt. A FileAlreadyExistsException is thrown if a file with the same name already exists.

2. Character Stream

The Character stream is used for 16-bit Unicode input and output operations. Character streams would be advantageous if we wanted to copy a text file containing characters from one source to another using streams because it deals with characters. Java characters are 2 bytes (or 16 bits) in size.CharacterStream classes are provided by the java.io package to overcome the limitations of ByteStream classes, which can only handle 8-bit bytes and are incompatible with working directly with Unicode characters. CharacterStream classes are used to work with Unicode characters that are 16 bits in length. They can work with characters, char arrays, and Strings.

The CharacterStream classes, on the other hand, are primarily used to read characters from the source and write them to the destination. CharacterStream classes are divided into two types for this purpose: Reader classes and Writer classes.

Character streams in Java, like Byte Streams, have a three-phase mechanism, as explained above.

There are numerous character stream classes in Java, but the most common ones are-

  • FileReader
    It is used to read two bytes at a time from the source. The function Object() { [native code] } for creating an instance of the FileReader class is as follows.

    Syntax of FileReader:

    FileFileWriter in = new FileWriter("path_to_file");
  • FileWriter
    It is used to write two bytes at a time to the destination. The function Object() { [native code] } for creating an instance of the FileWriter class is as follows.

    Syntax of FileWriter:

    FileWriter in = new FileWriter("path_to_file");

    Example of Character Java Stream:
    Below we have the code implementation and explanation

    import java.io.*;
    public class CharacterStreamExample {
    
       public static void main(String args[]) throws IOException {
          FileReader in = null;
          FileWriter out = null;
    
           // Reading source file using read method 
            // and write to file using write method
          try {
             in = new FileReader("source.txt");
             out = new FileWriter("destination.txt");
             int c;
             while ((c = in.read()) != -1) {
                out.write(c);
             }
          }
           finally {
             if (in != null) {
                in.close();
             }
             if (out != null) {
                out.close();
             }
          }
       }
    }
    

    Output:

    Hello from prepbytes ,this is  about character stream.

    Explanation
    This example uses Character Stream to copy the contents of one file to another. In the following example, we will create two FileReader and FileWriter objects. The names of the source and destination files are passed as parameters to the FileReader and FileWriter classes, respectively. The source file’s content is then copied to the destination file. Assume we’ve already created a file called source.txt with the following contents when we run the preceding program, it will generate a file called destination.txt with the same contents as source.txt. An exception of FileAlreadyExistsException is thrown if a file with the same name already exists.

Difference between Byte Stream and Character Stream:

Here we have the differences:

Byte Stream Character Stream
It operates on raw binary data and data is processed byte by byte It operates on text data and is processed character by character
Suitable for processing non-textual data such as images, videos, etc. Suitable for processing textual data such as documents, HTML, etc.
Input and Output operations are performed using InputStream and OutputStream classes Input and Output operations are performed using Reader and Writer classes
Suitable for low-level input and output operations Suitable for high-level input and output operations
Examples include FileInputStream and FileOutputStream Examples include FileReader and FileWriter

Conclusion
The java stream method aids in sequentially accessing a file. There are two types of java streams: Byte Stream and Character Stream. Byte streams are used to perform input and output of 8-bit bytes. When we want to read/write binary data, we can use byte streams. The character stream is used to perform 16-bit Unicode input and output operations. Character streams are used to read and write characters. Byte and Character Streams have a three-phase mechanism that includes Split, Apply, and Combine.FileInputStream and FileOutputStream are common classes for reading and writing data using byte streams.FileReader and FileWriter are commonly used to read and write data using character streams.

Frequently Asked Questions(FAQ)

Here are the FAQs on the java stream

Q1: What are InputStream and OutputStream classes in Java?
A: InputStream and OutputStream are abstract classes in Java that represent the input and output streams of bytes. They provide methods for reading and writing bytes from and to a source.

Q2: What are Reader and Writer classes in Java?
A: Reader and Writer are abstract classes in Java that represent the input and output streams of characters. They provide methods for reading and writing characters from and to a source.

Q3: What is the difference between InputStream/OutputStream and Reader/Writer classes?
A: InputStream/OutputStream classes operate on raw binary data, while Reader/Writer classes operate on text data. InputStream/OutputStream classes process data byte by byte, while Reader/Writer classes process data character by character. InputStream/OutputStream classes do not perform any character encoding or decoding, while Reader/Writer classes perform character encoding and decoding using specified character sets.

Q4: What are some examples of Byte Stream classes in Java?
A: Some examples of Byte Stream classes in Java include FileInputStream, FileOutputStream, BufferedInputStream, and BufferedOutputStream.

Q5: What are some examples of Character Stream classes in Java?
A: Some examples of Character Stream classes in Java include FileReader, FileWriter, BufferedReader, and BufferedWriter.

Leave a Reply

Your email address will not be published. Required fields are marked *