File.renameTo()没有任何效果

时间:2012-12-06 21:11:58

标签: java file formatting rename

我希望能够重命名文件夹列表以删除不需要的字符(例如,点和双空格必须成为单个空格)。

单击Gui中的按钮后,您将看到一个消息框,其中显示格式正确的名称,表示格式化正确并且调用了该功能。 当我查看我创建的测试文件夹时,名称不会更改(甚至在刷新后也不会更改)。使用硬编码字符串也不起作用。

我在俯瞰什么?

public void cleanFormat() {
    for (int i = 0; i < directories.size(); i++) {
        File currentDirectory = directories.get(i);
        for (File currentFile : currentDirectory.listFiles()) {
            String formattedName = "";
            formattedName = currentFile.getName().replace(".", " ");
            formattedName = formattedName.replace("  ", " ");
            currentFile.renameTo(new File(formattedName));
            JOptionPane.showMessageDialog(null, formattedName);
        }
    }
}

4 个答案:

答案 0 :(得分:7)

对于未来的浏览器:这是通过Assylias的评论修复的。您将在下面找到修复它的最终代码。

public void cleanFormat() {
    for (int i = 0; i < directories.size(); i++) {
        File currentDirectory = directories.get(i);
        for (File currentFile : currentDirectory.listFiles()) {
            String formattedName = "";
            formattedName = currentFile.getName().replace(".", " ");
            formattedName = formattedName.replace("  ", " ");
            Path source = currentFile.toPath();
            try {
                Files.move(source, source.resolveSibling(formattedName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

答案 1 :(得分:0)

好吧,首先File.renameTo试图在同一个文件系统上重命名文件。

以下内容来自java doc

Many aspects of the behavior of this method are inherently platform-dependent: 
The rename operation might not be able to move a file from one filesystem to 
another, it might not be atomic, and it might not succeed if a file with the 
destination abstract pathname already exists.

答案 2 :(得分:0)

首先检查返回值,如果重命名成功,File.renameTo返回true;否则是假的。例如。您无法在Windows上将文件从c:重命名/移动到d:。 最重要的是,改为使用Java 7的java.nio.file.Files.move。

答案 3 :(得分:0)

对getName()的调用只返回文件名,而不返回任何目录信息。因此,您可能正在尝试将文件重命名为其他目录。

尝试将包含目录添加到您传递给重命名的文件对象

currentFile.renameTo(new File(currentDirectory, formattedName));

还有其他人说你应该检查renameTo的返回值,这可能是假的,或者使用Files类中的新方法,我发现这些方法可以提供非常有用的IOExceptions。

相关问题