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()
永远不会引发异常。