Java:区分读取和关闭IOException?

Java:区分读取和关闭IOException?,java,ioexception,Java,Ioexception,以下是简化代码: public static void cat(File file) { try (RandomAccessFile input = new RandomAccessFile(file, "r")){ String line = null; while ((line = input.readLine()) != null) { System.out.println(line); } r

以下是简化代码:

public static void cat(File file) {
    try (RandomAccessFile input = new RandomAccessFile(file, "r")){
        String line = null;
        while ((line = input.readLine()) != null) {
            System.out.println(line);
        }
        return;
    } catch(FileNotFoundException a){
        ;//do something to recover from this exception.
    }catch(IOException b){
        ;//distinguish between close and readLine exception.
    }
}
有两种情况下,我们可能会收到
IOEception

  • 除了关闭
    输入
    外,一切正常
  • readLine
    抛出和
    IOException.
  • 那么如何区分这两种情况呢?有什么好方法可以做到这一点吗?或者我应该简化为对异常消息进行一些字符串比较,以区分这两个
    IOException


    谢谢!我只是找不到一个简单的方法来做这件事。

    你可以在回来之前做个标记

    public static void cat(File file) {
        boolean readAll = false;
        try (RandomAccessFile input = new RandomAccessFile(file, "r")){
            String line = null;
            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }
            readAll = true;
            return;
        } catch(FileNotFoundException a){
            ;//do something to recover from this exception.
        }catch(IOException b){
            ;//distinguish between close and readLine exception.
            if (readAll) ...
        }
    }
    
    实际上,此
    close()
    永远不会引发异常。