10.5. Copying Files, Strings, and URLs
Problem
You need to copy a file to another file, or you need to copy a file to a directory.
Solution
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.");
}Discussion
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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access