How do I create a copy of a file?

Category: commons.io, viewed: 8022 time(s).

This example shows how we can use the apache commons-io library to simplify a file copy process.

package org.kodejava.example.commons.io;

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

public class FileCopyExample 
{    
    public static void main(String[] args)
    {
        // The source file name to be copied.
        File source = new File("january.doc");
        
        // The target file name to which the source file will be copied.
        File target = new File("january-backup.doc");
        
        // A temporary folder where we are gonna copy the source file to.
        // Here we use the temporary folder of the OS, which can be obtained
        // using java.io.tmpdir property.
        File targetDir = new File(System.getProperty("java.io.tmpdir"));
        
        try
        {
            // Using FileUtils.copyFile() method to copy a file.
            System.out.println("Copying " + source + " file to " + target);
            FileUtils.copyFile(source, target);
            
            // To copy a file to a specified folder we can use the
            // FileUtils.copyFileToDirectory() method.
            System.out.println("Copying " + source + " file to " + targetDir);
            FileUtils.copyFileToDirectory(source, targetDir);
        } catch (IOException e)
        {
            // Errors will be reported here if any error occures during copying
            // the file
            e.printStackTrace();
        }
    }
}
Click here to lend your support to: Kode Java Org and make a donation at www.pledgie.com !

 

Uncensored Newsgroups
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Java Training

Sponsored Links

Our Friends

Statistics

Locations of visitors to this page
visitor stats