JAvaエレガントクローズioストリーム
2097 ワード
教科書を閉じる方法は,それぞれが空であるか否かを判断し,closeを呼び出すことである.それぞれ自分のtry catchで呼び出す必要があります
以下の図
ただしioオブジェクトはインタフェースCloseableから来ており,これにより閉じることができる.
apacheのioutilパッケージにより良好な方法を提供
以下の図
ソースコードの表示
つまりループオフ
以下の図
InputStream is=null;
InputStreamReader isr=null;
BufferedReader read=null;
try {
is = new FileInputStream(new File(""));
isr = new InputStreamReader(is);
read = new BufferedReader(isr);
String s = read.readLine();
} finally {
try {
if(null!=is){
is.close();
}
}catch (Exception e){
e.printStackTrace();
}
try {
if(null!=isr){
isr.close();
}
}catch (Exception e){
e.printStackTrace();
}
try {
if(null!=read){
read.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
ただしioオブジェクトはインタフェースCloseableから来ており,これにより閉じることができる.
apacheのioutilパッケージにより良好な方法を提供
以下の図
InputStream is=null;
InputStreamReader isr=null;
BufferedReader read=null;
try {
is = new FileInputStream(new File(""));
isr = new InputStreamReader(is);
read = new BufferedReader(isr);
String s = read.readLine();
} finally {
IOUtils.closeQuietly(read,isr,is);
}
ソースコードの表示
public static void closeQuietly(Closeable... closeables) {
if (closeables != null) {
Closeable[] arr$ = closeables;
int len$ = closeables.length;
for(int i$ = 0; i$ < len$; ++i$) {
Closeable closeable = arr$[i$];
closeQuietly(closeable);
}
}
}
public static void closeQuietly(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException var2) {
;
}
}
つまりループオフ