Java IO Tutorial

How to rename or move a file in Java

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/mkyong/newfolder/test1.txt");
  Path target = Paths.get("/home/mkyong/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/mkyong/hello.txt
  • To this /home/mkyong/newName.txt

  Path source = Paths.get("/home/mkyong/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/mkyong/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/mkyong/hello.txt
  • To this /home/mkyong/newfolder/hello.txt

  Path source = Paths.get("/home/mkyong/hello.txt");

  Path newDir = Paths.get("/home/mkyong/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/mkyong/hello.txt -> /home/mkyong/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.mkyong.io.file.FileRename.main(FileRename.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/mkyong/hello.txt");
    File target = new File("/home/mkyong/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/mkyong/newfolder/hello2.txt' already exists
	at org.apache.commons.io.FileUtils.moveFile(FileUtils.java:2012)
	at com.mkyong.io.file.FileRename.main(FileRename.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/mkyong/core-java

$ cd java-io

References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
17 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Thein Than Aung
7 years ago

//How does not work in window?Please tell me another way.Thank you so much.

import java.io.File;

public class RenameFileExample
{
public static void main(String[] args)
{

File oldfile =new File(“oldfile.txt”);
File newfile =new File(“newfile.txt”);

if(oldfile.renameTo(newfile)){
System.out.println(“Rename succesful”);
}else{
System.out.println(“Rename failed”);
}

}
}

Elm
3 years ago

when file already exists how can I rename then?

Sonam kumari
3 years ago
Reply to  mkyong

While renaming with the above format getting this error:-The method move(File, File) in the type Files is not applicable for the arguments (Path, Path, StandardCopyOption). Why i am getting this error can you please suggest me?

Sudhir
11 years ago

sometimes renameTo doesn’t work in windows.
I am still trying to find the the answer.
Can you please help me.

Thanks,
Sudhir

Harshil Sharma
8 years ago
Reply to  Sudhir

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.

Karren Omoto
12 years ago

Someone I work with visits your site frequently and recommended it to me to read also. The writing style is great and the content is relevant. Thanks for the insight you provide the readers!

ggfvf
3 years ago
package com.company;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;

public class FileMove {
    public static void main(String[] args) {

        String PathTargetName = "C:\\_All\\";  // this is the path file Location
        String FileName = "filename0.txt"; // this is the file or folder name

        String PathTargetMoveName = "C:\\_All\\_java\\";  // this is the path file Location

        File scourFile = new File(PathTargetName + FileName);
        File destinationFile = new File(PathTargetMoveName + FileName);

        try {
            Files.move(scourFile.toPath(),destinationFile.toPath());
            System.out.println("File move successful");

        } catch (IOException e) {
            System.out.println("An error occurred."); // this is the error system
            e.printStackTrace();
        }


    }
    }
DingThree
6 years ago

I have space in my file name, because of that i am not able to rename my file.could anyone please help on that?

jonathan
6 years ago

I use, Batch Rename Files Tool. You can easily found hier BatchRenameFiles.org that allows you to quickly rename all the files in a specified directory.

Saikat
10 years ago

sometimes it doesn’t work if the file in question is not accessible without admin permissions.

i.e if in windows explorer on trying to rename that file results in “permission from administrator” dialog

listened
10 years ago

I rename all very well,in windows 7 x64.

listened
10 years ago

That is helpful to me.Thank you.

jo
10 years ago

I have two files in the directory, the first one fails but the second is successful when using renameTo. Why is it like that?