【发布时间】:2021-10-12 02:21:01
【问题描述】:
我有源文件:
String sourceFileName = "C:\\Users\\blah\\source\\sourceFileName.csv"
我有目标文件:
String destinationFileName= "C:\\Users\\blah\\destination\\destinationFileName.csv"
我需要用源文件的内容覆盖目标文件的内容。但是,如果不删除目标文件,我无法弄清楚如何做到这一点。我能想到的所有方法都是简单地删除目标文件,然后用源文件替换它。我不能删除目标文件本身。我只能删除该文件的内容,然后粘贴新内容。我如何在 Java 中做到这一点?
我目前的方法
public static void overwriteTheContent(File sourceFile, String targetFileName) {
Path sourcePath = sourceFile.toPath();
Path targetPath = Paths.get(targetFileName);
File file = targetPath.toFile();
if(file.isFile()){
try {
Files.delete(targetPath); // I want to delete only the content, not the file !!!!!!!!
} catch (IOException e) {
e.printStackTrace();
}
}
try {
Files.move(sourcePath, targetPath);
} catch (IOException e) {
e.printStackTrace();
}
}
【问题讨论】:
-
新建一个文件并重命名。
-
你没有做任何特别的事情。只需打开文件进行输出并将数据写入文件即可。数据将被覆盖。
-
不知道该怎么做。缓冲作家?要不然是啥?蔚来?阿帕奇公地