How to rename all files of a folder using Java?
Last Updated :
24 Mar, 2018
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.
import java.io.File;
import java.io.IOException;
public class rename
{
public static void main(String[] argv) throws IOException
{
String folder_path =
"C:\\Users\\Anannya Uberoi\\Desktop\\myfolder" ;
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);
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
Please Login to comment...