java.io.SequenceInputStream — Everything You Need to Know

Here are two SequenceInputStream examples that you should know. First of all, a SequenceInputStream is an input stream object pointing to multiple input streams. It can read data from several InputStreams in the given order. You can combine files using this class.

In this tutorial, you'll know
  1. Constructors and Methods of java.io.SequenceInputStream class
  2. Printing data read from SequenceInputStream
  3. Writing SequenceInputStream to a file using FileOutputStream
The first example is on the first constructor which takes two InputStream objects and the second is on the last constructor which takes an enumeration of InputStream classes. Let us have a look.
public SequenceInputStream(InputStream s1,InputStream s2)
public SequenceInputStream(Enumeration<? extends InputStream> e)

Here are the methods of SequenceInputStream
// Returns the no.of bytes pointing to the SequenceInputStream
public int available()

// Close the SequenceInputStream
public void close()

// Read each byte from the SequenceInputStream and return it
public int read()

// Read upto len bytes from offset into a byte array b
public void read(byte[] b,int off,int len)

Example on SequenceInputStream using first Constructor

import java.io.*;
class SequenceInputStreamFirstCon
{
    public static void main(String args[]) throws Exception
    {
    SequenceInputStream sin=new SequenceInputStream(new FileInputStream(args[0]),new FileInputStream(args[1]));
   
    int k;
   
    FileOutputStream fout=new FileOutputStream("final.txt");
   
        while((k=sin.read())!=-1)
        {
            fout.write(k);
            System.out.print((char)k);
        }
   
    sin.close();
    fout.close();
    }
}

Example of SequenceInputStream class using second constructor

import java.io.*;
import java.util.*;
class SequenceInputStreamExample
{
    public static void main(String args[]) throws Exception
    {
    Vector<FileInputStream> v=new Vector<FileInputStream>();
        for(String k:args)
        v.add(new FileInputStream(k));
   
    SequenceInputStream sin=new SequenceInputStream(v.elements());
   
    int k;
   
    FileOutputStream fout=new FileOutputStream("final.txt");
   
        while((k=sin.read())!=-1)
        {
            fout.write(k);
            System.out.print((char)k);
        }
   
    sin.close();
    fout.close();
    }
}


Posted by at on

Tags: Java IO,