Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App

Related Articles

How to rename all files of a folder using Java?

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Often, when transferring files from the camera folder to a workspace where we would like to analyze the pictures, it becomes difficult to deal with long file and type them out again and again when testing them through a code. Also, the number of files might be too large to manually rename each one of them. Hence, it becomes a necessity to automate the renaming process.


Input : Read 50 files from the folder 
"C:\Users\Anannya Uberoi\Desktop\myfolder":
Snapshot 1 (12-05-2017 11-57).png
Snapshot 2 (12-05-2017 11-57).png
Snapshot 3 (12-05-2017 11-57).png
Snapshot 4 (12-05-2017 11-57).png   and so on.

Output :Renamed to
4.png   and so on.

// Java program to illustrate
// how to rename Multiple Files
// together using single program
public class rename
    public static void main(String[] argv) throws IOException
        // Path of folder where files are located
        String folder_path =
               "C:\\Users\\Anannya Uberoi\\Desktop\\myfolder";
        // creating new folder
        File myfolder = new File(folder_path);
        File[] file_array = myfolder.listFiles();
        for (int i = 0; i < file_array.length; i++)
            if (file_array[i].isFile())
                File myfile = new File(folder_path +
                         "\\" + file_array[i].getName());
                String long_file_name = file_array[i].getName();
                String[] tokens = long_file_name.split("\\s");
                String new_file_name = tokens[1];
                // file name format: "Snapshot 11 (12-05-2017 11-57).png"
                // To Shorten it to "11.png", get the substring which
                // starts after the first space character in the long
                // _file_name.
                myfile.renameTo(new File(folder_path +
                             "\\" + new_file_name + ".png"));


The files get renamed successfully.

Note: A double slash (\\) is required since one of the backslash (\) acts as an escape character and the other backslash (\) denotes directory change.

This article is contributed by Anannya Uberoi. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

My Personal Notes arrow_drop_up
Last Updated : 24 Mar, 2018
Like Article
Save Article
Similar Reads
Related Tutorials