3

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

单击 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

4 回答 4

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();
            }
        }
    }
}
于 2012-12-06T21:29:08.823 回答
0

好吧,首先File.renameTo是尝试重命名同一文件系统上的文件。

以下来自java文档

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.
于 2012-12-06T21:18:34.003 回答
0

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

于 2012-12-06T21:23:30.417 回答
0

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

尝试将包含目录添加到您传递给 rename 的文件对象中

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

也像其他人所说的那样,您应该检查 renameTo 的返回值,这可能是错误的,或者使用 Files 类中的新方法,我发现这些方法会抛出非常有用的 IOExceptions。

于 2012-12-06T21:27:18.677 回答