【问题标题】:File.renameTo() doesn't have any effectFile.renameTo() 没有任何效果
【发布时间】:2012-11-25 00:21:37
【问题描述】:

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

单击 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);
        }
    }
}

【问题讨论】:

  • 我认为您需要删除旧文件并创建新文件。
  • javadoc 中:注意Files 类定义了move 方法以独立于平台的方式移动或重命名文件。
  • 我在google上查了好几遍,发现以下代码:File f = new File("Rename.java~"); f.renameTo(new File("junk.dat"));除此之外从来没有其他任何东西,你的意思是它已被弃用还是什么?
  • @JeroenVannevel 它没有被弃用,它依赖于平台,并且可能会或可能不会根据各种因素工作。根据文档,Files#move 似乎更健壮。
  • @JeroenVannevel 您应该将答案作为答案发布(您可以回答自己的问题)。

标签: java file formatting rename


【解决方案1】:

对于未来的浏览器:这已通过 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();
            }
        }
    }
}

【讨论】:

    【解决方案2】:

    嗯,首先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.
    

    【讨论】:

      【解决方案3】:

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

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

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

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 2018-06-14
          • 2019-06-19
          • 2017-07-18
          • 2010-10-17
          • 2013-10-10
          • 2016-08-26
          • 2021-12-15
          • 2013-10-17
          • 1970-01-01
          相关资源
          最近更新 更多