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.
<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
//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”);
}
}
}
Try NIO
Files.move, it will throw an exception if failed to rename a file.when file already exists how can I rename then?
if the target file exists, and
REPLACE_EXISTINGoption is specified,Files.movewill replace it.Files.move(source, source.resolveSibling("newName.txt"),
StandardCopyOption.REPLACE_EXISTING);
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?
Files.move(Path, Path), NOT<span style="color: rgb(119, 119, 119);">Files.move(File, File)</span>, themovetakes path as arguments.sometimes renameTo doesn’t work in windows.
I am still trying to find the the answer.
Can you please help me.
Thanks,
Sudhir
Please do not use
File.renameTo(), read the api documentation.https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/io/File.html#renameTo(java.io.File)
Try NIO
Files.moveor Apache commons-ioFileUtilsMany 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.
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!
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(); } } }I have space in my file name, because of that i am not able to rename my file.could anyone please help on that?
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.
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
I rename all very well,in windows 7 x64.
That is helpful to me.Thank you.
I have two files in the directory, the first one fails but the second is successful when using renameTo. Why is it like that?