Recipe 11.3 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"));     } }



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net