2012-07-05 68 views
0

与此问题相关 Java writing to a deleted file 只在我的情况下我正在读取。并根据该评论,是的,Windows块删除和Unix不。并在unix下从来没有抛出任何IOException如何检测文件已从br.readline()循环内删除

该代码是一个穷人的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 
    } 
} 

明天我会尝试在睡觉前增加这个检查,也许是足够

if (!f.exists()) { 
    // file gone, aborting this thread 
    return; 
} 

任何人有其他想法?

回答

1

你可以观看使用WatchService API目录更改并采取相应的行动

+0

有趣的新东西。新的1.7似乎 – 2012-07-06 02:36:39

2

当你达到一个文件的末尾,BufferedReader中应该总是返回一个空是否已被删除或没有。它不是你应该检查的东西。

你能告诉我们一些代码,因为它很难阻止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."); 
    } 
} 

在窗口打印

AssertionError: Could not delete file. 

在Linux上打印

The end of file was reached. 
+0

谢谢,我不是很清楚,我已经添加了上面的代码 – 2012-07-06 02:35:51

+0

一旦你读完文件的结尾,你不能回去,再试一次。保持文件句柄打开的唯一方法是不读取文件的结尾。您可以通过在执行读取之前检查文件长度来完成此操作(这意味着您不能直接使用readLine) – 2012-07-06 05:27:54