与此问题相关 Java writing to a deleted file 仅就我而言,我正在阅读。根据该评论,是的,Windows 会阻止删除,而 Unix 不会。在 unix 下永远不会抛出任何 IOException
代码是穷人的tail -f
,其中我有一个java线程监视目录中的每个日志文件。我当前的问题是,如果文件被删除,我不会处理它。我需要中止并开始一个新线程或其他东西。我什至没有意识到这是一个问题,因为下面的代码在 Unix 下不会抛出异常
代码
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String line = null;
while (true) {
try {
line = br.readLine();
// will return null if no lines added
} catch (IOException e) {
e.printStackTrace();
}
if (line == null) {
// sleep if no new lines added to file
Thread.sleep(1000);
} else {
// line is not null, process line
}
}
明天我会尝试在 sleep 前添加此检查,也许就足够了
if (!f.exists()) {
// file gone, aborting this thread
return;
}
大家还有其他想法吗?
最佳答案
当到达文件末尾时,BufferedReader 应该始终返回 null,无论文件是否已被删除。这不是您应该检查的事情。
您能否向我们展示一些代码,因为很难阻止 BufferedReader 不返回 null?
这个程序
public class Main {
public static void main(String... args) throws IOException {
PrintWriter pw = new PrintWriter("file.txt");
for (int i = 0; i < 1000; i++)
pw.println("Hello World");
pw.close();
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
br.readLine();
if (!new File("file.txt").delete())
throw new AssertionError("Could not delete file.");
while (br.readLine() != null) ;
br.close();
System.out.println("The end of file was reached.");
}
}
在 Windows 上打印
AssertionError: Could not delete file.
在 Linux 上打印
The end of file was reached.
关于java - 如何检测文件已从 br.readline() 循环中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11352552/