【问题标题】:Rename file to uppercase in the same directory using Java使用Java将同一目录中的文件重命名为大写
【发布时间】:2014-08-30 15:50:58
【问题描述】:

我正在尝试使用 Java 重命名同一 Windows 目录中的文件 -

Before: -

C:/Temp/abG.txt

After: -

C:/Temp/ABG.TXT

我尝试过使用file.renameTo,但没有奏效。现在我正在尝试使用 -

Path source = file.toPath();
Files.move(source, source.resolveSibling(file.getName().toUpperCase()));

仍然没有运气。请帮忙。

【问题讨论】:

  • 这不起作用,因为 Windows 中的文件名不区分大小写。您需要先将其重命名为其他名称(例如“WindowsIsRubbish.txt”,然后就可以了。

标签: java windows file rename


【解决方案1】:

我没有尝试过跑步,但这在逻辑上应该可以工作。

  String newFilePath = oldFile.getAbsolutePath().replace(oldFile.getName(), oldFile.getName().toUpperCase());
  File newFile = new File(newFilePath);

  try {
    FileUtils.moveFile(oldFile, newFile);
  } catch (IOException e) {
    e.printStackTrace();
  }

希望这会有所帮助。

【讨论】:

  • 我会先添加一个检查,如果这是 Windows 或 Linux/Unix/Mac。如果是 Windows,应该有一个中间步骤将文件重命名为临时名称(我建议使用 System.currentMillis() 作为唯一名称),然后将该文件移动到大写名称下。否则,您的代码将无法在 Windows 下运行,因为它将大小写名称视为同一个文件。
  • @vishram0709 谢谢,但这并没有多大帮助:(
  • @carlspring 感谢更正System.currentTimeMillis() :)
【解决方案2】:

问题终于解决了。

似乎file.renameTo 在 Windows 上运行良好。我提到的路径是错误的,纠正它并且代码有效。

我使用的路径是C:/Temp/Folder,它应该是C:/Temp/Folder/

【讨论】:

    【解决方案3】:

    试试下面的

        String FILE_PATH = "C:\\Users\\HariBabuM\\Desktop\\file\\modify";
        File oldFile = new File(FILE_PATH, "fileWithCamelCase.txt");
        File newFile = new File(FILE_PATH, oldFile.getName().toLowerCase());
    
        oldFile.renameTo(newFile);
    

    【讨论】:

      猜你喜欢
      • 2011-05-15
      • 2010-12-10
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 2013-12-13
      • 2012-12-27
      • 1970-01-01
      • 2019-04-10
      相关资源
      最近更新 更多