【问题标题】:What is the easiest way to overwrite file content WITHOUT deleting the target file?在不删除目标文件的情况下覆盖文件内容的最简单方法是什么?
【发布时间】: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();
    }
}

【问题讨论】:

  • 新建一个文件并重命名。
  • 你没有做任何特别的事情。只需打开文件进行输出并将数据写入文件即可。数据将被覆盖。
  • 不知道该怎么做。缓冲作家?要不然是啥?蔚来?阿帕奇公地

标签: java file


【解决方案1】:

你在寻找这样的东西吗?:

    PrintWriter writer = new PrintWriter(FILE_PATH);
writer.print("");
writer.close();

然后:

PrintWriter writer2 = new PrintWriter(FILE_PATH);
writer.print("what you want to save to the file");

【讨论】:

    猜你喜欢
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 2011-10-30
    相关资源
    最近更新 更多