【问题标题】:how to detect file has been deleted from within br.readline() loop如何检测文件已从 br.readline() 循环中删除
【发布时间】:2012-07-05 21:04:10
【问题描述】:

与这个问题有关 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
    }
}

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

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

有人有其他想法吗?

【问题讨论】:

    标签: java unix io bufferedreader bufferedwriter


    【解决方案1】:

    当您到达文件末尾时,无论它是否已被删除,BufferedReader 都应始终返回 null。它不是你应该检查的东西。

    您能否向我们展示一些代码,因为很难阻止 BufferedReader 不返回空值?

    这个程序

    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.
    

    【讨论】:

    • 一旦您读取了文件的结尾,您将无法返回并重试。保持文件句柄打开的唯一方法是不读取文件末尾。您可以通过在执行读取之前检查文件长度来做到这一点(这意味着您不能直接使用 readLine)
    【解决方案2】:

    您可以使用WatchService API 来查看您的目录以了解更改并采取相应措施

    【讨论】:

    • 有趣的新东西。似乎是 1.7 的新功能
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 2012-07-09
    • 2012-07-20
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多