使用java重命名文件夹中的所有文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24199679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:45:35  来源:igfitidea点击:

Rename all files in a folder using java

javafiledirectoryrename

提问by Dimitri Dewaele

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

我们如何使用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

亲切的问候

采纳答案by Nirav Prajapati

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

我希望它会帮助你