tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 Java > IO > Copy File

Copy File 

The following example shows how to copy a file from source path to target path.

File Name  :  
com/bethecoder/tutorials/io/CopyFileTest.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.io;

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

public class CopyFileTest {

  /**
   @param args
   */
  public static void main(String[] args) {

    String srcFile = "C:\\abc.txt";
    String tgtFile = "C:\\NEW\\abc.copy.txt";
    
    copyFile(srcFile, tgtFile);
    System.out.println("File copied successfully.");
  }

  public static void copyFile(String srcFile, String tgtFile) {
    
    FileInputStream fis = null;
    FileOutputStream fos = null;
    
    try {
      fis = new FileInputStream(srcFile);
      fos = new FileOutputStream(tgtFile);

      byte [] buffer = new byte[1024];
      int read;

      while ((read = fis.read(buffer)) != -1) {
        fos.write(buffer, 0, read);
      }

      fis.close();
      fos.close();
      
    catch (FileNotFoundException e) {
      e.printStackTrace();
    catch (IOException e) {
      e.printStackTrace();
    }
      
  }
}
   

It gives the following output,
File copied successfully.



 
  


  
bl  br