Use FileUtils.copyFile()
and FileUtils.copyFileToDirectory() . The following code copies the file test.dat to test.dat.bak:
import org.apache.commons.io.FileUtils;
try {
File src = new File( "test.dat" );
file dest = new File( "test.dat.bak" );
FileUtils.copyFile( src, dest ) {
} catch( IOException ioe ) {
System.out.println( "Problem copying file." );
}You may also use FileUtils.copyFileToDirectory( ) to copy a
file to a directory. The following code copies the file test.dat to the directory ./temp:
try {
File src = new File( "test.dat" );
File dir = new File( "./temp" );
FileUtils.copyFileToDirectory( src, dir );
} catch( IOException ioe ) {
System.out.println( "Problem copying file to dir.");
}Quite often you need to write the contents of a String to a file. FileUtils.writeStringToFile( ) provides a
quick way to write textual content stored in a String to a File, without opening a Writer. The following code writes the contents
of the data String to the file
temp.tmp:
try {
String string = "Blah blah blah";
File dest = new File( "test.tmp" );
FileUtils.writeStringToFile( dest, string, ? );
}Another common task is storing the contents of a URL in a File. FileUtils.copyURLToFile( ) takes a URL object and stores the contents in a file.
The following code stores the contents of the New York
Times front page in a file times.html:
try {
URL src = new URL( "http://www.nytimes.com" );
File dest = new File( "times.html" );
FileUtils.copyURLToFile( src, dest );
} catch( IOException ioe ) {
System.out.println( "Error copying contents of a URL to a File." );
}