Renaming a File or Directory


File f = new File("myfile.txt"); File newFile = new File("newname.txt"); boolean result = f.renameTo(newFile);



In this phrase, we rename a file from myfile.txt to newname.txt. To accomplish this task, we have to create two File objects. The first File object is constructed with the current name of the file. Next, we create a new File object using the name we want to rename the file. We then call the renameTo() method on the original File object and pass in the File object that specifies the new filename. The renameTo() method will return a boolean value of true if the rename operation is successful and false if it fails for any reason.

This technique can also be used to rename a directory. The code for renaming a directory is exactly the same, except we pass the directory names to the File object constructors instead of file names. Here we show how this is done:

File f = new File("directoryA"); File newDirectory = new File("newDirectory"); boolean result = f.renameTo(newDirectory);


Remember that the new file or directory name must be specified in a File object that is passed to the renameTo() method. A common mistake is to attempt to pass a String containing the new file or directory name to the renameTo() method. Passing a String to the renameTo() method will generate a compile error.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

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