Java IO:异常处理的简介说明
下文笔者讲述java之IO包的异常处理简介说明,如下所示:
例: IO中的流,Reader,Writer在使用完毕后,我们应该调用close方法对其进行关闭操作,如下例所示:
例: IO中的流,Reader,Writer在使用完毕后,我们应该调用close方法对其进行关闭操作,如下例所示:
InputStream input = new FileInputStream("E:\\test\\testInformation.txt");
int data = input.read();
while(data != -1) {
//do something with data...
doSomethingWithData(data);
data = input.read();
}
input.close();
以上代码存在一个问题,当doSomethingWithData()方法运行异常时,则会导致input.close()无法运行 我们需将以上代码修改为以下样式 在finally中加入input连接的释放操作,当然为了避免程序报错,我们还需在finally中加入try catch
InputStream input = null;
try{
input = new FileInputStream("c:\\data\\input-text.txt");
int data = input.read();
while(data != -1) {
//do something with data...
doSomethingWithData(data);
data = input.read();
}
}catch(IOException e){
//do something with e... log, perhaps rethrow etc.
} finally {
if(input != null)
input.close();
}
finally {
try{
if(input != null)
input.close();
} catch(IOException e){
//do something, or ignore.
}
}
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。


