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")); } }
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.