Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename all files in a folder using java [duplicate]

How can we rename all files in a folder using java?

C:/temp/pictures/1.jpg
C:/temp/pictures/2.jpg
C:/temp/pictures/3.jpg
C:/temp/pictures/4.jpg
C:/temp/pictures/5.jpg

Rename to

C:/temp/pictures/landscape_1.jpg
C:/temp/pictures/landscape_2.jpg
C:/temp/pictures/landscape_3.jpg
C:/temp/pictures/landscape_4.jpg
C:/temp/pictures/landscape_5.jpg

Kind regards

like image 468
Dimitri Dewaele Avatar asked Jan 22 '26 10:01

Dimitri Dewaele


1 Answers

Take a look at below code which check file in the folder and rename it.

File dir = new File("D:/xyz");

if (dir.isDirectory()) { // make sure it's a directory
    for (final File f : dir.listFiles()) {
        try {
            File newfile =new File("newfile.txt");

            if(f.renameTo(newfile)){
                System.out.println("Rename succesful");
            }else{
                System.out.println("Rename failed");
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

I Hope It Will Help You

like image 97
Nirav Prajapati Avatar answered Jan 24 '26 02:01

Nirav Prajapati