【问题标题】:How to read/write a file in Java如何在 Java 中读/写文件
【发布时间】:2016-08-10 08:45:51
【问题描述】:

我想根据一些正则表达式替换文件中的一些项目。为此:

  • 我每行读取文件行
  • 对于每一行,我检查正则表达式并执行替换
  • 每一行都写入一个字符串数组

当这一切完成后,我尝试删除文件(以便用替换的行重新创建它)。

由于某种原因,这不起作用:Java 似乎保留了该文件的句柄,即使在 BufferedReader 已关闭之后也是如此。

有人对这个(新手)问题有解决方案吗?

代码摘录:

      Pattern oDatePattern   = Pattern.compile("at \\d{2}:\\d{2}:\\d{2} "); // meaning: "at xx:xx:xx"
      Pattern oTimePattern   = Pattern.compile("Kernel time [0-9]*\\.?[0-9]+ User time: [0-9]*\\.?[0-9]+"); // "[0-9]*\.?[0-9]+" stands for any floating point number
      Pattern oMemoryPattern = Pattern.compile("\\([0-9,A-F]*\\)"); // "[0-9,A-F]*" stands for any hexadecimal number 
      Matcher oDateMatcher;
      Matcher oTimeMatcher;
      Matcher oMemoryMatcher;

      List<String> sLog_Content = new ArrayList<String>();

      BufferedReader br = new BufferedReader(new FileReader(sLp_LogFile));
      try {
        String sLine = br.readLine();

        while (sLine != null) {
          System.out.println("ORIG : " + sLine);
          oDateMatcher = oDatePattern.matcher(sLine);
          sLine        = oDateMatcher.replaceAll("at <timestamp> ");
          oTimeMatcher = oTimePattern.matcher(sLine);
          sLine        = oTimeMatcher.replaceAll("Kernel time <Kernel_Time_usage> User time: <User_Time_usage>");
          oMemoryMatcher = oMemoryPattern.matcher(sLine);
          sLine          = oMemoryMatcher.replaceAll("<Memory_Address>");
          System.out.println("REPL : " + sLine);
          sLog_Content.add(sLine);
          sLine = br.readLine();
        }
      } finally {
        br.close();
      }

      System.out.println("All lines are read and regex replaced, try to delete the file");

      File tst_File = new File(sLp_LogFile);
      if (tst_File.exists()) {
        System.out.println(sLp_LogFile + " exists");
      } else {
        System.out.println(sLp_LogFile + " does not exist");
      }

      if (tst_File.delete()) {
        System.out.println(sLp_LogFile + " is deleted");
      } else {
        System.out.println(sLp_LogFile + " is not deleted");
      }

输出日志:

ORIG : Reading buffer 1 (0000000002ED0070) at 15:40:44 (index 125999, size 4410000 lines 126000, total lines read 126000)
REPL : Reading buffer 1 <Memory_Address> at <timestamp> (index 125999, size 4410000 lines 126000, total lines read 126000)
...
ORIG : Sending buffer 1 (0000000002ED0070) at 15:40:44 (index 125999, size 4410000, lines 126000, total lines sent 126000)
REPL : Sending buffer 1 <Memory_Address> at <timestamp> (index 125999, size 4410000, lines 126000, total lines sent 126000)
...
ORIG : Kernel time 0.2808 User time: 0.312
REPL : Kernel time <Kernel_Time_usage> User time: <User_Time_usage>
...
All lines are read and regex replaced, try to delete the file
D:\Logfile_lp.log exists
D:\Logfile_lp.log is not deleted

【问题讨论】:

  • 我有以下建议:保留 FileReader 引用并关闭它。如果您使用 Java 7 或更高版本,则可以使用 TRY-with-resources 语法。
  • @brso05 - 没必要。对BufferedReaderclose() 调用将在FileReader 上调用close()
  • 你能试试Files.delete(path)吗? (需要java7+)
  • 作为一个测试,我保留了 FileReader 并关闭了那个,但这并没有解决问题。
  • 我尝试使用“文件”,但它似乎不起作用(未找到文件)。

标签: java io file-handling


【解决方案1】:

一种可能的解释是您的应用程序在其他地方打开了文件。

或者它可能是打开文件的另一个应用程序。

或者也许应用程序/用户有权读取文件但不能删除它。


我同意使用Files.delete ..的建议。

【讨论】:

  • 事实上,这个文件是使用以下代码创建的:exitcode = Runtime.getRuntime().exec(cmdline).waitFor();。我假设waitFor()方法等待整个过程完成,这意味着相应的文件已经写完,并且它的句柄已经被释放。
【解决方案2】:

我认为您的代码没有问题。

看似关闭BufferReader 确保文件已关闭。 (参见this response)。

也许你可以试试Files.delete cf this response
它将通过抛出不同的异常来提供有关删除失败的更多信息。

【讨论】:

    【解决方案3】:

    我是一个初学者,我不知道很多事情你。但是,如果我知道的话,您应该先将更改保存为临时文件。之后,您将再次读取临时文件,稍后您将写入您的真实文件。希望我的评论对你有所帮助。

    【讨论】:

      【解决方案4】:

      下午好, 我要感谢大家寻找这个问题的解决方案。不幸的是,问题不是基于 Java:我尝试写入的文件是由重定向 cmd /c &lt;program&gt;.exe &gt;&gt; &lt;output&gt;.log 创建的,而且似乎 Windows 没有将输出缓冲区完全刷新到输出文件,从而产生了问题。

      我目前正在使用以下(非常肮脏的)解决方法来解决这个问题:

      boolean bFile_can_be_opened = false;
      while (!bFile_can_be_opened) {
        try {
          fwLog2 = new FileWriter(sLp_LogFile, true);
          bFile_can_be_opened = true;
        }
        catch (Exception e)
        {}
      }
      

      可以在以下新的 StackOverflow 问题下找到有关此问题的更多信息:How to release a file, locked by the application, in Java

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-18
        • 2019-06-04
        • 1970-01-01
        • 2014-03-20
        相关资源
        最近更新 更多