Thursday, October 24, 2013

Java Program for concating File content

Write a JAVA Program which reads a number of text files from the command line and concatenates the contents of the files into the last file entered on the command line.

Example:

Java Concatenate src1.txt src2.txt src3.txt dest.txt

All the contents of the source files should be concatenated and written in destination file.

Solution:


 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class FileConcatination {

    public static void main(String[] args){
        if(args.length==0){
            System.out.println("Please enter file(s) name in proper format.");
            return;
        }

        //File object
        File[] file = new File[25];
        int i=0;
        for(i=0;i<args.length;i++){
            file[i] = new File(args[i]);
            //Checking file
            if(file[i].exists()){
                System.out.printf("\n%s exists.",file[i].getName());
                if(file[i].isDirectory()){
                    System.out.println(" But it is not a file.");
                }
            }
            else
                System.out.printf("\n%s not exists.",file[i].getName());    
        }
        System.out.println();

        //Reading all files and writing it to the last file
        try{
            //Opening last file for writing
            FileOutputStream fWrite = new FileOutputStream(args[args.length-1]);

            //Reading other files
            int r=0;
            FileInputStream[] fread = new FileInputStream[25];
            for(i=0;i<args.length-1;i++){
                fread[i] = new FileInputStream(args[i]);

                //Writing files.
                while((r = fread[i].read())!=-1){
                    fWrite.write((char)r);
                }
            }
            System.out.println("\nWriting complected.");
            //Closing files
            fWrite.close();
            for(i=0;i<args.length-1;i++)
                fread[i].close();
        }

        catch(Exception e) {
            System.out.println("\nWriting failed.");
        }
    }
}

No comments:

Post a Comment