gpt4 book ai didi

java - renameTo() 不起作用

转载 作者:行者123 更新时间:2023-12-01 22:38:55 25 4
gpt4 key购买 nike

我需要通过将文件名中的 - 替换为 _ 来重命名文件。

假设文件名是ab-9.xml,它应该是ab_9.xml

renameTo() 对我不起作用。还有其他方法可以做到这一点吗?这是我的代码:

File replaceCheracter(File file) {
File oldPath = new File(file.getPath())
String filePath = file.getPath()
if(filePath.contains("-")){
String newFilePath = filePath.replace("-", "_")
if(oldPath.renameTo(newFilePath)) {
System.out.println("renamed");
} else {
System.out.println("Error");
}
}
return oldPath
}

最佳答案

您应该考虑使用 java.nio.file封装:

final Path file = Paths.get("path\\to\\your-file.txt");

Files.move(file, file.resolveSibling(file.getFileName().toString().replace("-", "_")));

使用了非常方便的功能Path#resolveSibling()作为 Files#move() 的第二个参数.

说明:

  • Path#resolveSibling() 获取调用它的 Path 对象的目录路径,并交换最后一部分(实际的文件名)作为提供的参数(在本例中是新的、修改后的文件名)。

使用此行为作为 Files#move() 的第二个参数将导致源目录和目标目录相同的移动,因此它只会重命名文件。

参见The Java Tutorials - File I/O有关此的更多信息。

关于java - renameTo() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26485428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com