【发布时间】: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 - 没必要。对
BufferedReader的close()调用将在FileReader上调用close()。 -
你能试试
Files.delete(path)吗? (需要java7+) -
作为一个测试,我保留了 FileReader 并关闭了那个,但这并没有解决问题。
-
我尝试使用“文件”,但它似乎不起作用(未找到文件)。
标签: java io file-handling