Write a java program to merge the content of file(2 source 1 destination)

/*

Example - Hello.txt  contains -   Hello welcome to Java. 

                 Country.txt contains - India is my country.

                merge.txt  contains - Hello welcome to Java. India is my country.

*/

 import java.io.*;

import java.util.*;


class Merge

{

File f1,f2,f3;

Merge()

{

Scanner s=new Scanner(System.in);

System.out.print("Enter path of 1st File: ");   

String path1=s.nextLine();   // to get path of 1st file

System.out.print("Enter file name of 1st File: "); 

String file1=s.nextLine();   // to get name of file

System.out.print("Enter path of 2nd File: ");

String path2=s.nextLine();   // to get path of 2nd file

System.out.print("Enter file name of 2nd File: ");

String file2=s.nextLine();   // to get file name

System.out.print("Enter destination path : ");

String desp=s.nextLine();    // to get designation path

System.out.print("Enter destination file name: ");

String desf=s.nextLine();   // to get file name

// File is a class and it's constructor have 2 parameters File(path_of_file , file_name) 

                f1=new File(path1,file1);

f2=new File(path2,file2);

f3=new File(desp,desf);

}

void disp()

{

try

{

if(f3.exists())

{

                            // FileInputStream is used to read the data from files in byte

FileInputStream fin=new FileInputStream(f3);

System.out.print("Content of merged file");

while(true)

{

int i=fin.read(); // read method is use to read single character from file

if(i==-1)   // if there is no other characters in file read method return -1

{

break;

}

System.out.print((char)i);   //  to print  character

}

fin.close();  // to close the file

}

}

catch(Exception e)

{

System.out.println(e);

}

}

void merging()

{

try

{

FileInputStream fin=new FileInputStream(f1);

                         //  FileOutputStream  is used to write the data from files in byte

FileOutputStream fout=new FileOutputStream(f3);

while(true)

{

int i=fin.read();

if(i==-1)

break;

fout.write(i);

}

fin.close();

fin=new FileInputStream(f2);

// fout=new FileOutputStream(f3);

while(true)

{

int i=fin.read();

if(i==-1)

break;

fout.write(i);

}

fin.close();

fout.close();

}

catch(Exception e)

{

System.out.print(e);

}

}

}

class TestMerge

{

public static void main(String args[])

{

Merge obj=new Merge();

obj.merging();

obj.disp();

}

}

0 Comments