How to copy a file in java

In this section you will learn about how to copy a content of one file to another file. In java, File API will not provide any direct way to copy a file.

How to copy a file in java

In this section you will learn about how to copy a content of one file to another file. In java, File API will not provide any direct way to copy a file.

How to copy a file in java

How to copy a file in java

In this section you will learn about how to copy a content of one file to another file. In java, File API will not provide any direct way to copy a  file.  What we can do is, read a content of one file through FileInputStream and write it into another file through FileOutPutStream. There are some open source library available like "Apache commons IO " , in that there is one class called FileUtils, which provide file related operation. In the FileUtils class there is a method   FileUtils.copyFile(source file , destinationfile), which allows you to copy a file. In another way we can copy using File I/o Stream.

Example:  Java Code to copy a content of one file to another file.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
 public class CopyFile
  {
   
    public static void main(String args[])throws IOException
  {
      
      String  src ="C://Documents and Settings//satya//Desktop//file//hello.txt";  // path of source file is assigned to src string.
      String  dest = "C://Documents and Settings//satya//Desktop//file//hi.txt";       //path of destination file is assigned to dest.
      InputStream in = new FileInputStream(src);
      OutputStream out = new FileOutputStream(dest);
      byte[] b = new byte[1024];             // creating a byte type buffer to store the content of file.
       int len;
      while ((len = in.read(b)) > 0)
        {
           out.write(b, 0, len);  // 0 here indicates the position to writing in the target file.
           }
          in.close();
         out.close(); 
         System.out.println("Done");
       }
   }

When we execute the above program the content of "hello.txt" is copied to "hi.txt" as we have given path for the both source file and destination file which is stored in src and dest,. then reading the content using while loop storing in buffer. After that just write the content to target file using out.write() in which starting from 0 to the length len of the file.

 Output: After compiling and executing of above program.

Download SourceCode