Open In App

How to rename all files of a folder using Java?

Last Updated : 24 Mar, 2018
Improve
Improve
Like Article
Like
Save
Share
Report


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.

Examples:

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
1.png
2.png
3.png
4.png   and so on.




// Java program to illustrate
// how to rename Multiple Files
// together using single program
import java.io.File;
import java.io.IOException;
  
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];
                System.out.println(long_file_name);
                System.out.print(new_file_name);
  
                // 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"));
            }
        }
    }
}


Output:

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads