O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Renaming a File

Problem

You need to change a file’s name on disk.

Solution

Use a java.io.File object’s renameTo( ) method.

Discussion

For reasons best left to the gods of Java, the renameTo( ) method requires not the name you want the file renamed to, but another File object referring to the new name. So to rename a file you must create two File objects, one for the existing name and another for the new name. Then call the renameTo method of the existing-name’s File object, passing in the second File object. This is easier to see than to explain, so here goes:

import java.io.*;

/**
 * Rename a file in Java
 */
public class Rename {
    public static void main(String[] argv) throws IOException {

        // Construct the file object. Does NOT create a file on disk!
        File f = new File("Rename.java~"); // backup of this source file.

        // Rename the backup file to "junk.dat"
        // Renaming requires a File object for the target.
        f.renameTo(new File("junk.dat"));
    }
}

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required