Rename or Move a File or Directory in Java
Learn to rename a file or directory at a specified path or move to a new directory in Java. We will learn to use the classes from Standard IO, New IO, Guava and Commons IO.
As the method name suggests, renameTo() renames the file to the new name or moves the file to a new directory location.
- The renameTo() returns true or false denoting if the renaming succeeded or not.
- It throws SecurityException if there are write access problems with the old or the new file.
File originalFile = new File("c:/temp/demo.txt"); File renamedFile = new File("c:/temp/demoNew.txt"); File movedFile = new File("c:/temp/moved/demoNew.txt"); boolean isCopied = originalFile.renameTo(renamedFile); boolean isMoved = renamedFile.renameTo(movedFile); System.out.println(isCopied); //true System.out.println(isMoved); //true
The Files.move() is similar to renameTo() except it works with the Path instances instead of File instances.
- The move() method moves or renames a file to a target file. Moving a file will copy the last-modified-time to the target file if supported
- If given file and target files are same then this method has no effect.
- If target file already exists then move() will fail. We can use StandardCopyOption.REPLACE_EXISTING in such cases.
- To perform the whole rename or move operation as single atomic operation, we can use StandardCopyOption.ATOMIC_MOVE option. If the move cannot be performed as an atomic file system operation (incase of two different filesystems) then AtomicMoveNotSupportedException is thrown.
- If the file is a symbolic link then the symbolic link itself, not the target of the link, is moved.
- Renaming a directory can fail if it requires to move the files in a new location i.e. directory is being moved to a location. It it is a simple directory renaming in same location in the filesystem, it will succeed.
Path file = Path.of("c:/temp/demo.txt"); //Rename in same directory Files.move(file, file.resolveSibling("demoNew.txt")); //Move to new directory Path newDir = Path.of("c:/temp/moved/"); Files.move(file, newDir.resolve(file.getFileName()), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
This Files.move() method moves a file from one path to another. This is applicable to renaming and moving, both operations.
We should be careful that the destination path must be the target path for the file itself; not just the new name for the file or the path to the new parent directory.
File originalFile = new File("c:/temp/demo.txt"); File renamedFile = new File("c:/temp/demoNew.txt"); com.google.common.io.Files.move(originalFile, renamedFile); com.google.common.io.Files.move(renamedFile, movedFile);
The FileUtils class provides many methods to move or rename the files and directories as per requirements.
- moveDirectory(File srcDir, File destDir) – moves a directory to destination and deletes the source directory.
- moveDirectoryToDirectory(File src, File destDir, boolean createDestDir) : Moves a directory to another directory and takes an option to create the new directory or not. If createDestDir is false and new directory cannot be created then IOException will be thrown.
- moveFile(File srcFile, File destFile, CopyOption… copyOptions) : moves a file preserving file attributes with optional copy options.
- moveFileToDirectory(File srcFile, File destDir, boolean createDestDir) : moves a file into a specified directory.
- moveToDirectory(File src, File destDir, boolean createDestDir) : moves a file or directory to the destination directory.
FileUtils.moveFile(originalFile, renamedFile); File targetDirectory = new File("c:/temp/moved/"); FileUtils.moveFileToDirectory(originalFile, targetDirectory, true);
In this short tutorial, we learned to rename a file or directory or move it to a new location with different copy options.
Though standard IO and new IO classes provide all kinds of capabilities, Common IO’s FileUtils class provides very specific methods for each kind of operation. These specific method names communicate the intent very well.
How to rename a File using Java
Renaming a file is typically done through the operating system shell program or the corresponding window interface. However, Java has the predefined classes, File and Files, with shell commands, which are methods of the classes. The class, File is in the java.io.* package, which has to be imported for its methods to be used. The class, Files (ending with ‘s’) is in the java.nio.file.* package, which also has to be imported, for its own methods to be used.
To rename a file, the user or programmer should have the execute permission of the directory that directly has the file. Also, if the new name already exists, as a name of another file in the same directory, the renaming should not take place.
The Files class has more advantages over the File class. For example, if another file with the same name already exists, the File class has the choice to replace the other file. It has an exception (error) handling scheme, while File does not have an effective exception handling scheme.
This article explains how to rename a file through Java, using the File and the Files classes.
Class File
This class has the method called renameTo() , to rename a file. To use this method, an object of the type, File, must be instantiated from the class, File. It is this object that will employ the method. A File object is an object that has a file path. An example of a file path is:
where the names are directories, except “demo.txt” which is a filename. The syntax of a constructor to create (instantiate) a File object is:
where pathname is a path like that given above but has to be in quotes.
The syntax for the renameTo method of the File object is:
where dest (for destination) is a new File object of the same path but ending with the new filename. Note: the filename at the end of a path is part of the path (officially). This means that dest is another File object that should refer to the same file. So if the name demo.txt is to be changed to actual.txt, the dest would be:
The method returns true if renaming took place and false otherwise. If false is returned, it will not easily be possible to know why the file could not be renamed.
The following Java program renames the file, demo.txt to actual.txt, in accordance with the above scheme:
import java.io.* ;
public class TheClass {
public static void main ( String [ ] args ) {
File fileObjOld = new File ( «/home/user/dir1/demo.txt» ) ;
File fileObjNew = new File ( «/home/user/dir1/actual.txt» ) ;
if ( fileObjOld. renameTo ( fileObjNew ) ) {
System . out . println ( «File renamed successfully.» ) ;
} else {
System . out . println ( «Error: File could not be renamed!» ) ;
}
}
}
File renamed successfully.
Class Files
The class, Files in the java.nio.file.* package has only static methods. “static” means the class does not have to be instantiated for any of its methods to be used. The class has the static method called move(), to move a file from one place to another, with the possibility of giving the destination file a new name. In order to use this method, an object of the type, Path, has to be obtained (returned) from the class, Paths. It is this object that will employ the method. A Path object is similar to a File object: it is an object that has a file path. An example of a file path is:
where the names are directories, except “demo.txt” which is a filename. The Paths class has only static methods. One of them is:
Again, “static” means that a Paths object does not have to be created (instantiated), for the get() method to be used. The many arguments of the get() method mean that the many strings would be joined for a path to be obtained. A string literal is in double-quotes.
The Paths class is also in the java.nio.file.* package, which has to be imported.
The syntax for the move() method of the Files class is:
It throws an IOException. So this statement should be in a try block, followed by a catch-block. The source refers to the original path but must be a Path object. Target refers to the new path and must also be a Path object. The CopyOption argument can be omitted as in the following program.
In order to rename a file with the move() method, the file will be moved to itself and give it a new name. So, the path for the source should end with the original filename, and the path for the target should end with the new filename. So if the name demo.txt is to be changed to actual.txt, then the path for the target would be:
The move method throws an exception, which is an object of the IOException class. So, the package java.io.*, which has the IOException class, has to be imported.
The following Java program, renames the file, demo.txt to actual.txt, in accordance with this scheme:
import java.io.* ;
import java.nio.file.* ;
public class TheClass {
public static void main ( String [ ] args ) {
Path source = Paths. get ( «/home/user/dir1/demo.txt» ) ;
Path target = Paths. get ( «/home/user/dir1/actual.txt» ) ;
try {
Files. move ( source, target ) ;
} catch ( IOException e ) {
e. printStackTrace ( ) ;
}
}
}
If there is no output for this particular program, then the file has been renamed.
Conclusion
Renaming a file is typically done through the operating system shell program or the corresponding window interface. However, Java has the predefined classes, File and Files, with shell commands, which are methods of the classes. The class, File is in the java.io.* package, which has to be imported for its methods to be used. The class, Files is in the java.nio.file.* package, which also has to be imported, in order for its own methods to be used.
In order to use the File class, an object of File type has to be instantiated. This object will use its renameTo() method to rename the file. In order to use this method, two File objects, effectively path objects, are needed. The path objects differ only at their ends-of-path, with the old and new filenames. The File object is of the File class, which is in the java.io.* package.
On the other hand, the Files class uses its static move() method to rename a file indirectly. This move() method moves a file onto itself but with a new name. In order to use this method, two Paths objects are needed. The path object differs only at their ends-of-path, with the old and new filenames. The Path object is of the Paths class, which is in the java.nio.file.* package. The Paths class has only static methods, of which the one to obtain a path object is get().
About the author
Chrysanthus Forcha
Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.