+92 332 4229 857 99ProjectIdeas@Gmail.com

Copy One File To Another File (Java)



The following example shows you how to copy one file contents to another file. And also shows how to append data in file.

Code

// Copy (overWrite) one file Contents to Another
 public static void copyFile(File readingFile , File writingFile) {
             
    try
        {
                    
          String str = null;
          FileReader fr = new FileReader(readingFile);
          BufferedReader br = new BufferedReader(fr);
          PrintWriter pw = new PrintWriter(writingFile);
                    
             while ( ( str = br.readLine() ) != null ) {
                    
                      pw.println(str);
             }
                    
           pw.flush();
           pw.close();
           br.close();
                    
      } catch (IOException ioEx) {
                        
             System.out.println(ioEx);
     }
 }
        
//Reading File And Returning Its All Data In One String
 public String readFile (FileReader fr) {
      
   try
       {
             
         String str = null , fullFile = "";
         BufferedReader br = new BufferedReader(fr) ;

           while ( ( str = br.readLine() ) != null ) {
                    
                fullFile = fullFile + str; // reading All Data into one string
           }
                    
         return fullFile;
                    
    } catch (IOException ioEx) {
              
         System.out.println(ioEx);
   }
                    
         return null;
}

// Writing all data which is returned By readFile () Function
public static void appendFile(File readingFile , File appendingFile) {
             
   try
       {
                    
        FileReader fr = new FileReader(readingFile);
         //true means to append data in file
        BufferedWriter bw = new BufferedWriter( new FileWriter (appendingFile, true) ); 
        String getAllData = null;
              // getting data from function readFile() and Storing to string getAllData
        getAllData = readFile(fr);
                    
           if ( getAllData != null) {
                    
                bw.write(getAllData);
           }
                    
          bw.close();
                    
     } catch (IOException ioEx) {
                          
         System.out.println(ioEx);
    } 
 }

public class Test {

       public static void main(String[] args) {
      
               copyFile(new File("D:\\abc.txt"),new File("D:\\abc2.txt"));
               appendFile(new File("D:\\temp.txt"),new File("D:\\abc2.txt"));
      }
}

0 comments: