How to rename a file using java.io packages?

How to rename a file using packages java.io?

+3
source share
4 answers
File oldfile = new File(old_name);
File newfile = new File(new_name);
boolean Rename = oldfile.renameTo(newfile);

The boolean Renamewill be true if it successfully renamed the old file.

+8
source
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"));
      }
    }

Link: http://www.java2s.com/Code/Java/File-Input-Output/RenameafileinJava.htm

+6
source

java.io.File renameTo.

+3

FWIW, Java 7 , , , java.nio.file.Files#move:

java.nio.file.Files.move(oldPath, newPath, StandardCopyOption.ATOMIC_MOVE)

, , , java.io.File#renameTo:

: , , , . , , .

, Files .

java.nio.file.Files#move CopyOption, (, , , ..)

0

All Articles