【问题标题】:How to replace a file in Java如何在 Java 中替换文件
【发布时间】:2016-09-04 15:41:37
【问题描述】:

我正在尝试通过创建一个临时文件、操作文本、然后删除原始文件以将其替换为临时文件来重写文件的内容。方法如下:

private void deleteLine(String lineToRemove){
    File inputFile = new File("./src/class1.txt");
    File tempFile = new File("./src/tempFile.txt");

    BufferedReader reader;
    reader = new BufferedReader(new FileReader(inputFile));

    BufferedWriter writer;
    writer = new BufferedWriter(new FileWriter(tempFile));

    String currentLine;

    while((currentLine = reader.readLine()) != null) {
        if(!currentLine.trim().equals(lineToRemove)){
            writer.write(currentLine +     System.getProperty("line.separator"));
        }
    }
    writer.close();
    reader.close();

    System.out.println("Input to temp1: " + tempFile.renameTo(inputFile));
}

在测试这个方法时,我发现除了最后两行,一切都按预期工作,它们都返回 false。我的 class1.txt 文件在方法启动时存在,但 tempFile.txt 不存在。

【问题讨论】:

  • 为什么要用两个文件?您可以将字符串 (lineToRemove) 替换为空字符串 ("")
  • 你对“./src/class1.txt”文件有足够的权限吗?大多数情况下,由于缺少写权限,系统无法覆盖文件。
  • 是的,我确实有足够的权限。正如我所说,我可以写入文件,但删除和替换函数返回 false。

标签: java file bufferedreader bufferedwriter


【解决方案1】:

下面的代码就像一个魅力:

private static void copyFiles(File source, File dest) throws IOException {
    Files.move(source.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

【讨论】:

    【解决方案2】:

    您的tempFile.txt 在那里,但您没有看到它:),尝试刷新您的项目(我假设您使用的是 eclipse)。

    Right click 在项目文件夹上 > Refresh

    您将看到该文件。

    您还需要一个inputFile.delete(); 电话

    writer.close();
    reader.close();
    
    inputFile.delete();
    
    System.out.println("Input to temp1: " + tempFile.renameTo(inputFile));
    

    【讨论】:

      【解决方案3】:

      使用try-with-resourcesStreamsNIO.2 的工作解决方案,其中有一些benefits

      Path inputPath = Paths.get("foo.txt");
      Path outputPath = Paths.get("foo.txt.tmp");
      try (Stream<String> lineStream = Files.lines(inputPath);
           BufferedWriter writer = Files.newBufferedWriter(outputPath)) {
           lineStream
              .filter(line -> !"pattern".equals(line.trim()))
              .forEach(line -> {
                 try {
                    writer.append(line);
                    writer.newLine();
                 } catch (IOException e) {
                    throw new UncheckedIOException(e);
                 }
              });
      }
      Files.delete(inputPath);
      Files.move(outputPath, inputPath);
      

      【讨论】:

        【解决方案4】:

        使用 apache commons io 进行 java 复制/替换文件操作

        private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
            FileUtils.copyFile(source, dest);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-12-07
          相关资源
          最近更新 更多