Rename All Files in a Directory

Rename All Files in a Directory:

This code is tested in Windows OS.  Do the necessary changes as per your requirement.

import java.io.File;
class renameFiles{
public static void main(String args[]){
String dir="D:\\FF\\NF1";
String addPrefix="Pref_";
File dirFile,dirFile1;
File oldfile, newfile;
String newname;
String filenames[];
int i, count;

dirFile = new File(dir);
if (!dirFile.exists() || !dirFile.isDirectory()) {
System.err.println("File not exist or not a directory ");
}

filenames = dirFile.list();
for(i = count = 0; i < filenames.length; i++) {
if (filenames[i].equals(".")) continue; // must skip . and .., cannot rename them
if (filenames[i].equals("..")) continue;
dirFile1 = new File(dir+"\\"+filenames[i]); //if there is a directory then skip it
if (!dirFile1.isDirectory()){
oldfile = new File(dirFile, filenames[i]); // create a File object for existing file
newname = addPrefix + filenames[i]; // next line creates the new name
newfile = new File(dirFile, newname); // create a File object for new name
if (oldfile.renameTo(newfile)) count++; // attempt to rename existing file
else {
System.err.println("Unable to rename " + oldfile);
}
}
}
}
}

Thanks 🙂

About Bhabani 86 Articles
Bhabani has 10 plus years of experience in Data warehousing and Analytics projects that has span across multiple domains like Travel, Banking and Financial, Betting and Gaming Industries. Solution areas he focuses on designing the data warehouse and integrating it with cloud platforms like AWS or GCP. He is also a Elite level contributor at OTN forum more than 9 years. He loves to do experiment and POC on different integration tools and services. Some of his favorite skills are Redshift, Big Query, Python, Apache Airflow, Kafka, HDFS, Map Reduce ,HIVE, Habse, Sqoop, Drill, Impala.

5 Comments

  1. Hi Bhabanirann,
    Thanks for this brilliant content. Can you explain when this Java can be used. In this scenario, a korn shell or windows batch script will do.

    Also, Can you explain loading multiple files into the same target. For ex, there are
    a.csv,b.csv and c.scv files are present in a folder. They needed to be loaded into the same table.
    How can we loop through a specific folder and load the files.

    Can you please email me to abbi1680@gmail.com

    Thanks
    Seshi

    • Keep in mind that ” always try to avoid OS specific commands/script”. Its because in case migration from unix to windows all unix script will fail and vice versa.

      The most universal language is java and supported in all platform. So if your codes are on java then there wont be any problem in case of migration. This can be done in groovy as well but limited.

      Regarding your last question I am working on this and will post as soon as i can.

Leave a Reply

Your email address will not be published.


*