我一直在尝试复制一个文件,但在同一个 windows 目录中更改了它的名称,但我没有成功。
我不能只复制同目录下的文件,因为windows规定同目录下的两个文件不能重名。
我不允许复制到另一个目录然后重命名,然后再将它移回同一目录。
而且我在 File.class
中没有看到任何有用的实现。
尝试过类似的方法,但没有成功:
File file = new File(filePath);
File copiedFile = new File(filePath);
//then rename the copiedFile and then try to copy it
Files.copy(file, copiedFile);
最佳答案
最初的尝试是使用 Path
视情况而定:
Path file = Paths.get(filePath);
String name = file.getFileName().toString();
String copiedName = name.replaceFirst("(\\.[^\\.]*)?$", "-copy$0");
Path copiedFile = file.resolveSibling(copiedName);
try {
Files.copy(file, copiedFile);
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
关于java - 如何在Windows中的同一目录中复制给定不同名称的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55163968/