Common Java Cookbook

Edition: 0.19

Download PDF or Read on Scribd

Download Examples (ZIP)

10.5. Copying Files, Strings, and URLs

10.5.1. Problem

You need to copy a file to another file, or you need to copy a file to a directory.

10.5.2. 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.");
}

10.5.3. 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 {
    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." );
}

Creative Commons License
Common Java Cookbook by Tim O'Brien is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License.
Permissions beyond the scope of this license may be available at http://www.discursive.com/books/cjcook/reference/jakartackbk-PREFACE-1.html. Copyright 2009. Common Java Cookbook Chunked HTML Output. Some Rights Reserved.