Renaming File in Java
The renameTo() method changes the name of a file. For example, to change the name of the file src.txt
in the current working directory to dst.txt, you would write:
File src = new File("src.txt");
File dst = new File("dst.txt");
src.renameTo(dst);
As well as renaming the source file, renameTo() moves the source file from its original directory to the directory specified by the destination argument if the destination file is in a
different directory than the source file. For example, to move a file src to the directory /usr/tmp on a Unix system without changing the file's name, do this:
File dest = new File("/usr/tmp/" + src.getName());
src.renameTo(dest);
If dest already exists, then it is overwritten by the source file (permissions permitting; otherwise, an exception is thrown). If src is successfully renamed, the method returns true.
If the security manager doesn't allow the program to write to both the source file and the destination file, a security exception is thrown. Otherwise, the method returns false.
However, this behavior is unreliable and platform-dependent. For instance, renameTo() moves files if, and only if, the directory structure specified in the dest File object already
exists. It's best not to rely on this method for more than renaming a file in the same directory.
public boolean renameTo(File dest)
The method f1.renameTo(f2) tries to change the name of f1 to f2. This may involve a move to a different directory if the filenames so indicate.
To move a file f1 to the directory /usr/tmp, you would write the following code:
File dest = new File("/usr/tmp/" + f1.getName());
f1.renameTo(dest);
If f2 already exists, then it is overwritten by f1 (permissions permitting). If f1 is renamed, the method returns true. Otherwise it returns false.