Java:区分读取和关闭IOException?

时间:2018-07-13 04:30:01

标签: java ioexception

这是简化的代码:

hidden

在两种情况下,我们可能会得到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. } }

  1. 除了关闭IOEception以外,其他所有方法都可以正常工作。
  2. input抛出并readLine

那么如何区分这两种情况?有什么好的方法吗?还是应该简化一下异常消息的字符串比较以区分这两个IOException.

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

1 个答案:

答案 0 :(得分:0)

您可以在返回前进行​​标记

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) ...
    }
}