简体   繁体   中英

How to rename a file using java.io packages?

如何使用java.io包重命名文件?

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

使用java.io.FilerenameTo方法。

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 (eg, what you want to happen if the file already exists, whether it must be done atomically, etc.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM