如何用Java读/写文件

如何用Java读/写文件,java,io,file-handling,Java,Io,File Handling,我想根据一些正则表达式替换文件中的某些项。为此: 我每行读一行文件 对于每一行,我检查正则表达式并执行替换 每一行都写在一个字符串数组中 当所有这些都完成后,我尝试删除该文件(以便用替换的行重新创建它) 出于某种原因,这不起作用:Java似乎在该文件上保留了一个句柄,即使在BufferedReader关闭之后也是如此 有人能解决这个(新手)问题吗 代码摘录: Pattern oDatePattern = Pattern.compile("at \\d{2}:\\d{2}:\\

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

  • 我每行读一行文件
  • 对于每一行,我检查正则表达式并执行替换
  • 每一行都写在一个字符串数组中
当所有这些都完成后,我尝试删除该文件(以便用替换的行重新创建它)

出于某种原因,这不起作用: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");
      }
Pattern-oDatePattern=Pattern.compile(“at\\d{2}:\\d{2}:\\d{2}”);//意思是:“在xx:xx:xx”
Pattern oTimePattern=Pattern.compile(“内核时间[0-9]*\\.?[0-9]+用户时间:[0-9]*\.?[0-9]+”;//“[0-9]*\.?[0-9]+”表示任何浮点数
模式oMemoryPattern=Pattern.compile(“\\([0-9,A-F]*\\)”);//“[0-9,A-F]*”表示任何十六进制数
Matcher-oDateMatcher;
Matcher-oTimeMatcher;
匹配器,匹配器;
List sLog_Content=new ArrayList();
BufferedReader br=新的BufferedReader(新文件读取器(sLp_日志文件));
试一试{
字符串sLine=br.readLine();
while(sLine!=null){
System.out.println(“源代码:+sLine”);
oDateMatcher=oDatePattern.matcher(sLine);
sLine=oDateMatcher.replaceAll(“at”);
oTimeMatcher=oTimePattern.matcher(sLine);
sLine=oTimeMatcher.replaceAll(“内核时间用户时间:”);
oMemoryMatcher=oMemoryPattern.matcher(sLine);
sLine=oMemoryMatcher.replaceAll(“”);
System.out.println(“REPL:+sLine”);
sLog_内容。添加(sLine);
sLine=br.readLine();
}
}最后{
br.close();
}
System.out.println(“读取所有行并替换正则表达式,尝试删除文件”);
文件tst_File=新文件(sLp_日志文件);
如果(tst_File.exists()){
System.out.println(sLp_日志文件+“存在”);
}否则{
System.out.println(sLp_日志文件+“不存在”);
}
if(tst_File.delete()){
System.out.println(sLp_日志文件+“已删除”);
}否则{
System.out.println(sLp_日志文件+“未删除”);
}
输出日志:

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
ORIG:15:40:44读取缓冲区1(000000000 2ED0070)(索引125999,大小4410000行126000,总行读取126000)
回复:读取缓冲区1(索引125999,大小4410000行126000,总行读取126000)
...
源:在15:40:44发送缓冲区1(000000000 2ED0070)(索引125999,大小4410000,行126000,发送的行总数126000)
回复:在发送缓冲区1(索引125999,大小4410000,行126000,发送的行总数126000)
...
源:内核时间0.2808用户时间:0.312
回复:内核时间用户时间:
...
读取所有行并替换正则表达式,请尝试删除该文件
D:\Logfile\u lp.log存在
D:\Logfile\u lp.log未被删除

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

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

或者,应用程序/用户有权读取该文件,但无权删除该文件



我同意使用
文件的建议。删除

我认为您的代码没有问题

关闭
BufferReader
确保文件已关闭。(比照)

也许你可以试试cf。

它将通过抛出不同的异常来提供有关删除失败的更多信息。

我是一个初学者,我不知道与您类似的事情。但如果我知道的没错,你应该先把你的更改保存到临时文件中。之后,您将再次读取临时文件,稍后将写入实际文件。我希望我的评论能对你有所帮助。

下午好, 我要感谢你们大家为这个问题寻找解决办法。不幸的是,问题不是基于Java的:我试图写入的文件是通过重定向
cmd/c.exe>.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问题:

我有以下建议:保留FileReader引用并将其关闭。如果您使用Java 7或更高版本,则可以使用TRY with resources语法。@brso05-不需要。
BufferedReader
上的
close()
调用将调用
FileReader
上的
close()
。可以尝试
文件。删除(路径)
?(需要java7+)作为测试,我保留了FileReader并关闭了它,但这并没有解决问题。我尝试使用“文件”,但似乎不起作用(找不到文件)。事实上,此文件是使用以下代码创建的:
exitcode=Runtime.getRuntime().exec(cmdline.waitFor()。我假设
waitFor()
方法等待整个过程完成,这意味着相应的文件已完全写入,其句柄已释放。