Friday, June 8, 2012

Write a program to copy a file to another file using java.io package classes. Get the file names at run time and if the target file existed then ask confirmation to overwrite and take necessary actions.?


♣♣♣ WRITE A PROGRAM TO COPY A FILE TO ANOTHER FILE USING JAVA.IO PACKAGE CLASSES. GET THE FILE NAMES AT RUN TIME AND IF THE TARGET FILE EXISTED THEN ASK CONFIRMATION TO OVERWRITE AND TAKE NECESSARY ACTIONS. ♣♣♣

import java.lang.*;
import java.io.*;

class pro13
{
        public static void main(String ar[]) throws IOException
        {
               InputStreamReader a =new InputStreamReader(System.in);
               BufferedReader b=new BufferedReader(a);
                int i;
                FileInputStream fin=null;
                FileOutputStream fout=null;
                String filename=null;
                try
                {
                        System.out.print("\n\tEnter the file name to copy to another file : ");
                        filename=b.readLine();
                        try
                        {
                                fin=new FileInputStream(filename);
                        }
                        catch(Exception e)
                        {
                                System.out.println("\n\tFile Not Found");
                                return;
                        }
                        try
                        {
                                System.out.print("\n\tEnter the file name to copy : ");
                                filename=b.readLine();
                                fout=new FileOutputStream(filename);
                        }
                        catch(Exception e)
                        {}
                }
                catch(Exception e)
                {}
                try
                {
                        do
                        {
                                i=fin.read();
                                if(i!=-1)
                                fout.write(i);
                        }while(i!=-1);
                       
System.out.println("\n\tFile copied to "+filename+" Sucessfully");
                }
                catch(IOException e)
                {
                        System.out.println("\n\tFile Error");
                }
                fin.close();
                fout.close();
        }
}


OUTPUT :-
                                   
                        Enter the file name to copy to another file : c:\test.txt
                       
                        Enter the file name to copy : c:\hello.txt

                        File copied to c:\hello.txt successfully

                       
                        Enter the file name to copy to another file : c:\tests.txt
                        File Not Found

No comments:

Post a Comment