How to rename a file using java.io
开发者_如何学Cpackages?
File oldfile = new File(old_name);
File newfile = new File(new_name);
boolean Rename = oldfile.renameTo(newfile);
The boolean Rename
will be true if it successfully renamed the oldfile.
import java.io.File;
import java.io.IOException
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"));
}
}
Reference: http://www.java2s.com/Code/Java/File-Input-Output/RenameafileinJava.htm
Use the java.io.File
's renameTo
method.
FWIW, as of Java 7 and later, the preferred answer for this should probably be to use java.nio.file.Files#move
:
java.nio.file.Files.move(oldPath, newPath, StandardCopyOption.ATOMIC_MOVE)
The reason why one would prefer this approach is because of this documented behavior in java.io.File#renameTo
:
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.
Note that the Files class defines the move method to move or rename a file in a platform independent manner.
When using java.nio.file.Files#move
, one can specify standard CopyOption
parameters that indicate more nuanced behavior (e.g., what you want to happen if the file already exists, whether it must be done atomically, etc.)
精彩评论