Rename all files in a folder using java [duplicate

2019-05-27 04:26发布

问题:

This question already has an answer here:

  • Rename a file using Java 14 answers

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

回答1:

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