ProblemYou need to change a file's name on disk. SolutionUse a java.io.File object's renameTo( ) method. DiscussionFor 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")); } } |