使用来自不同扩展名的文件的字符串重命名文件

Renaming a file with a string from a file of different extension

我需要重命名一个名为 .txt.afp 文件。我在尝试让这个东西工作时偶然发现了很多 "solutions",但没有任何帮助。

假设我在 C:/test/a/Mytes t.txt 中有一个 txt 文件,我想重命名 C:/files/b/Testf ile.afp 中的 .afp 文件。这就是我正在尝试做的(根据本网站上找到的解决方案),但它不起作用。我剪切了 .txt 文件的扩展名,只得到文件名:

String fileNameNoExt=fileName.substring(0, fileName.lastIndexOf('.'));
//fileName is .txt file name
File file = new File(afpSRC, afpName);
file.renameTo(new File(afpSRC, fileNameNoExt + ".afp"));

afpSRC 包含 .afp 文件所在文件夹的路径,afpName 是文件名。

谁能告诉我为什么这不起作用并且 .afp 文件名保持不变?

可能是因为 File file = new File(afpSRC, afpName); 没有引用现有文件。

我怀疑 afpSRC 不是父路径或 afpName 不是文件名。或者两者兼而有之?

要进行调试,您应该先检查该文件是否存在。
如果不存在,则抛出异常。
除了以任何方式(调试和最终代码)之外,您应该通过 renameTo() 检查返回值并相应地处理它。

这是一个示例代码:

String fileNameNoExt=fileName.substring(0, fileName.lastIndexOf('.'));
//fileName is .txt file name
File file = new File(afpSRC, afpName);
if (!file.exists()){
   throw new RuntimeException("file not found = " + file);
}

boolean isRenamed = file.renameTo(new File(afpSRC, fileNameNoExt + ".afp"));
System.out.println("isRenamed = " + isRenamed);
if (!isRenamed){
   // handle the problem
}

如果您使用 Java NIO 工具,您将能够通过异常获取信息来解释重命名失败的原因。

Files.move(Path from, Path to, CopyOption... options) throws IOException

String fileNameNoExt=fileName.substring(0, fileName.lastIndexOf('.'));
Path afpPathName = Paths.get(afpSRC, afpName);
Path newPathName = Paths.get(afpSRC, fileNameNoExt + ".afp");
Files.move(afpPathName, newPathName);