Moving a File or Directory


File file = new File("filename"); File dir = new File("directoryname"); boolean success =    file.renameTo(new File(dir, file.getName())); if (!success) {    // File was not successfully moved }



The renameTo() method of the File class allows us to move a file or directory into a different directory. In this phrase, we create a File object to represent the file or directory we are moving. We create another File object representing the destination directory that we are moving the file or directory into. We then call the renameTo() method on the file being moved and pass it a single File object parameter. The File object passed as a parameter is constructed using the destination directory and the original file name. If the move operation is successful, the renameTo() method will return a boolean true value. If the move fails, a boolean false is returned.

When you use the renameTo() method, keep in mind that many aspects of its behavior are platform dependent. Some of these platform dependent behaviours are noted in the JavaDoc for this method. They include the following:

  • The rename operation might not be able to move a file from one filesystem to another.

  • The rename operation might not be atomic. This means that the implementation of the rename operation may consist of multiple steps at the operating system level. This could lead to problems in severe conditions such as power failure between steps.

  • The rename operation might not succeed if a file with the destination abstract pathname already exists.

When using this method, you should always check the return value to make sure that the rename operation was successful.




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