How do I copy a file?
Author: Deron Eriksson
Description: This Java tutorial describes how to copy a file using Commons IO.
Tutorial created using: Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)


The copyFile() method of the FileUtils class of the ApacheSW Commons IOS library can be used to make a copy of a file. It takes the source file as its first argument and the destination file as its second argument. The CopyFileTest class demonstrates this.

CopyFileTest.java

package test;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class CopyFileTest {

	public static void main(String[] args) throws IOException {

		File file1 = new File("test1.txt");
		File file2 = new File("test1-copy.txt");
		checkExists(file1);
		checkExists(file2);

		System.out.println("\nCopying " + file1.getName() + " to " + file2.getName() + "\n");
		FileUtils.copyFile(file1, file2);

		checkExists(file1);
		checkExists(file2);

	}

	public static void checkExists(File file) {
		System.out.println(file.getName() + " exists? " + file.exists());
	}

}

The CopyFileTest class takes the test1.txt file and makes a copy of it called test1-copy.txt. As we can see from the console output below, test1-copy.txt didn't exist before the copy but did exist after the copy.

Results

test1.txt exists? true
test1-copy.txt exists? false

Copying test1.txt to test1-copy.txt

test1.txt exists? true
test1-copy.txt exists? true