In Java, we can use the NIO Files.move(source, target) to rename or move a file.

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

  //...

  Path source = Paths.get("/home/tvt/workspace/favtuts/newfolder/test1.txt");
  Path target = Paths.get("/home/tvt/workspace/favtuts/newfolder/test2.txt");

  try{

    Files.move(source, target);

  } catch (IOException e) {
    e.printStackTrace();
  }

1. Rename a file in the same directory.

1.1 This example renames a file in the same directory, keeping the same file name.

  • Rename a file from this /home/tvt/workspace/favtuts/hello.txt
  • To this /home/tvt/workspace/favtuts/newName.txt
  Path source = Paths.get("/home/tvt/workspace/favtuts/hello.txt");

  try{

    // rename a file in the same directory
    Files.move(source, source.resolveSibling("newName.txt"));

  } catch (IOException e) {
    e.printStackTrace();
  }

1.2 If the target file exists, the Files.move throws FileAlreadyExistsException.

java.nio.file.FileAlreadyExistsException: /home/tvt/workspace/favtuts/newName.txt
	at java.base/sun.nio.fs.UnixCopyFile.move(UnixCopyFile.java:450)
	at java.base/sun.nio.fs.UnixFileSystemProvider.move(UnixFileSystemProvider.java:267)
	at java.base/java.nio.file.Files.move(Files.java:1421)
	at com.mkyong.io.file.FileRename.main(FileRename.java:26)

1.3 If the REPLACE_EXISTING option is specified, and the target file exists, the Files.move will replace it.

import java.nio.file.StandardCopyOption;

  Files.move(source, source.resolveSibling("newName.txt"),
              StandardCopyOption.REPLACE_EXISTING);

2. Move a file to a new directory.

2.1 This example moves a file to a new directory, keeping the same file name. If the target file exists, replace it.

  • Move a file from this /home/tvt/workspace/favtuts/hello.txt
  • To this /home/tvt/workspace/favtuts/newfolder/hello.txt
  Path source = Paths.get("/home/tvt/workspace/favtuts/hello.txt");

  Path newDir = Paths.get("/home/tvt/workspace/favtuts/newfolder/");

  //create the target directories, if directory exits, no effect
  Files.createDirectories(newDir);

  Files.move(source, newDir.resolve(source.getFileName()),
              StandardCopyOption.REPLACE_EXISTING);

2.2 If target directory not exits, the Files.move throws NoSuchFileException.

java.nio.file.NoSuchFileException: /home/tvt/workspace/favtuts/hello.txt -> /home/tvt/workspace/favtuts/newfolder/hello2.txt
  	at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
  	at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
  	at java.base/sun.nio.fs.UnixCopyFile.move(UnixCopyFile.java:478)
  	at java.base/sun.nio.fs.UnixFileSystemProvider.move(UnixFileSystemProvider.java:267)
  	at java.base/java.nio.file.Files.move(Files.java:1421)
  	at com.favtuts.io.file.FileRenameMove.main(FileRenameMove.java:23)

3. Move file – Apache Commons IO

3.1 The Apache FileUtils.moveFile uses a “copy and delete” mechanism to rename or move a file. Furthermore, it did a lot of checking and ensuring the correct exception is thrown, a reliable solution.

pom.xml

  <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.7</version>
  </dependency>
import org.apache.commons.io.FileUtils;

    //...

    File source = new File("/home/tvt/workspace/favtuts/hello.txt");
    File target = new File("/home/tvt/workspace/favtuts/newfolder/hello2.txt");

    try {

        FileUtils.moveFile(source, target);

    } catch (IOException e) {
        e.printStackTrace();
    }

3.2 If the target file exists, it throws FileExistsException.

org.apache.commons.io.FileExistsException: Destination '/home/tvt/workspace/favtuts/newfolder/hello2.txt' already exists
	at org.apache.commons.io.FileUtils.moveFile(FileUtils.java:2012)
	at com.mkyong.io.file.FileRenameMove.main(FileRenameMove.java:39)

3.3 If the target directory does not exist, create it.

4. File.renameTo (Legacy IO)

The legacy IO File.renameTo() is not reliable, not recommend to use, read the api documentation.

If the File.renameTo() failed to rename or move the file, it will return a false, no exception thrown, often time, we have no idea what went wrong.

Download Source Code

$ git clone https://github.com/favtuts/java-core-tutorials-examples

$ cd java-io/file

Leave a Reply

Your email address will not be published. Required fields are marked *