【问题标题】:How do I batch rename files in java? [duplicate]如何在java中批量重命名文件? [复制]
【发布时间】:2014-07-19 00:39:43
【问题描述】:

我有一个文件列表:

"f1.txt" “f2.txt” “f3.txt” “f4.txt”

并想批量重命名为:

"file1.txt" “文件2.txt” “文件 3.txt” "file4.txt"

理想情况下,我希望将其作为一个小型 java 程序来完成,但不介意在 Windows PowerShell 之类的东西中完成。

提前致谢

【问题讨论】:

  • 这是 java 还是 powershell 的问题?

标签: java powershell batch-rename renaming


【解决方案1】:

只需构建一个获取两个参数 oldname 和 newname 的函数并将其放入其中

 // File  with old name
        File file = new File("oldname");

        // File  with new name
        File file2 = new File("newname");
        if(file2.exists()) throw new java.io.IOException("file exists");

        // Rename file 
        boolean success = file.renameTo(file2);
        if (!success) {

        }
    java.io.FileWriter out= new java.io.FileWriter(file2, true );//append=yes 

【讨论】:

  • 您使用的是 JDK 7 之前的代码。 Java 7 中已经存在类似(并且更好)的方法。
【解决方案2】:

Powershell,将重命名$path中的所有文件:

$path = "C:\pathToFiles"
cd $path
ls | % { Rename-Item $_.Name $_.Name.replace("f","file") }

【讨论】:

    猜你喜欢
    • 2015-08-15
    • 2016-04-09
    • 1970-01-01
    • 2011-12-18
    • 2018-04-26
    • 2010-10-17
    • 1970-01-01
    • 2019-03-16
    • 1970-01-01
    相关资源
    最近更新 更多