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


The copyFileToDirectory() method of the FileUtils class of the ApacheSW Commons IOS library allows us to copy a file to a directory. It takes the source file as its first parameter and the destination directory as its second argument. If the destination directory doesn't exist, it will be created. The CopyFileToDirectoryTest class demonstrates this.

CopyFileToDirectoryTest.java

package test;

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

import org.apache.commons.io.FileUtils;

public class CopyFileToDirectoryTest {

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

		File file = new File("test1.txt");
		File destinationDir = new File("test-directory");

		FileUtils.copyFileToDirectory(file, destinationDir);

	}

}

Before executing CopyFileToDirectoryTest, I had the test1.txt source file located at the root level of my project.

'testing' project

After executing CopyFileToDirectoryTest, you can see that the test-directory directory was created, with a copy of test1.txt in that directory.

test1.txt copied to test-directory