gpt4 book ai didi

java - 如何在 Java 中读取/写入文件

转载 作者:行者123 更新时间:2023-11-30 06:10:02 26 4
gpt4 key购买 nike

我想根据一些正则表达式替换文件中的一些项目。为了做到这一点:

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

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

出于某种原因,这不起作用: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

最佳答案

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

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

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


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

关于java - 如何在 Java 中读取/写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36696930/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com