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

3

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

重命名为

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

亲切问候。

你可以在这里找到使用Java重命名文件的方法:https://dev59.com/sHM_5IYBdhLWcg3w8IHR - Bernard
你可以在这里找到另一个清晰的例子:http://www.roseindia.net/java/example/java/io/RenameFileOrDir.shtml - Alexandru Cimpanu
1个回答

13

请看下面的代码,它可以检查文件夹中的文件并将其重命名。

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();
        }

我希望它能帮助你


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接