Java-Concatenating Files

Concatenating Files

It is possible to combine two or more input streams (files) into a single input stream (file). This process is known as concatenation of files and is achieved using the SequencelnputStream class. One of the constructors of this class takes two InputStream objects as arguments and combines them to construct a single input stream.

The following program illustrates the process of concatenation. The program creates two objects of class Filelnputstream for the files “data1.da” and “data2.da“. The two Filelnputstream objects ‘fis1′ and ‘fis2′ are used as arguments to the SequencelnputStream constructor to obtain a single input stream object ‘sis‘. The file sis now contains the contents of ‘fis1′ and ‘fis2′. Then uses a while loop to read all bytes in the ‘sis‘ and write them through the FileInputStream ‘fis‘. Finally, the program reads ‘fis‘ and displays its bytes on the screen.

Program

final

Program Source

import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.SequenceInputStream;
import java.io.IOException;

class Javaapp {
    
    public static void main(String[] args) throws IOException {
        
        FileInputStream fis1 = new FileInputStream("data1.da");
        FileInputStream fis2 = new FileInputStream("data2.da");
        SequenceInputStream sis = new SequenceInputStream(fis1,fis2);
        
        FileOutputStream fos = new FileOutputStream("data3.da");
        int getData;
        while((getData = sis.read())!=-1)
        {
            fos.write(getData);
        }
        sis.close();
        fis1.close();
        fis2.close();
        fos.close();
        FileInputStream fis = new FileInputStream("data3.da");

        while((getData = fis.read())!=-1)
        {
            System.out.println(getData);
        }
        fis.close(); 
    }
}

Leave a Comment