Java:区分读取和关闭IOException?

Java : distinguish between read and close 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);
        }
        return;
    } catch(FileNotFoundException a){
        ;//do something to recover from this exception.
    }catch(IOException b){
        ;//distinguish between close and readLine exception.
    }
}

有两种情况我们可能会得到IOEception

  1. 除了关闭 input.
  2. 之外一切正常
  3. readLine 抛出并且 IOException.

那么如何区分这两种情况呢?有没有好的方法来做到这一点?或者我应该减少对异常消息进行一些字符串比较以区分这两个 IOException?

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

你可以在return

之前做一个flag
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) ...
    }
}