Friday 12 December 2014

Using single line to Copy a File in Java


You can do copy a file using single line of code using FileUtils from Apche. To do this you have to get the jar file and import to your project. Now by calling a function in your Java code you can copy a file, and the function is "FileUtils.copyFile(source file, destination path)" for example look below code.
 

Code:

import java.io.File;
import java.io.IOException;
import java.util.Date;
import org.apache.commons.io.FileUtils;


public class copy {
    public static void main(String args[]){
        try {
            String source = "/home/arul/Desktop/IJITCS.pdf";
            String destination = "/home/arul/Test/";
            File f1 = new File(source);
            String fname = f1.getName();
            System.out.println("File :: "+fname);
            File f2 = new File(destination+fname);
            //Copy a file
            FileUtils.copyFile(f1, f2);
            System.out.println("File copied Sucessfully !!! ");
        } catch (Exception e) {
            System.err.println("ERR "+e.getMessage());
        }
    }
}

Output:

File :: IJITCS-V4-N10-9.pdf

File copied Sucessfully !!! 

Jar File:

Click here to get Jar and add it to your library.