Java

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:

/home/user/dir1/demo.txt

where the names are directories, except “demo.txt” which is a filename. The syntax of a constructor to create (instantiate) a File object is:

public File(String pathname)

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:

public boolean renameTo(File dest)

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:

/home/user/dir1/actual.txt

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!");
            }
        }
    }

The output should be:

File renamed successfully.

everything being equal.

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:

/home/user/dir1/demo.txt

where the names are directories, except “demo.txt” which is a filename. The Paths class has only static methods. One of them is:

public static Path get(String first, String... more)

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:

public static Path move(Path source, Path target, CopyOption... options) throws IOException

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:

/home/user/dir1/actual.txt

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.