Java7のtry-with-resources構文でcloseし忘れを防ぐ
DBやらfileやらにアクセスする際に
FileInputStream is = null;
FileOutputStream os = null;
try{
is = new FileInputStream("hoge.txt");
InputStreamReader ir = new InputStreamReader(is,"Shift_JIS");
os = new FileOutputStream("hige.txt");
OutputStreamWriter ow = new OutputStreamWriter(os,"UTF-8");
int tmp;
while((tmp = ir.read()) != -1){
ow.write(tmp);
}
}catch(Exception e){
e.printStackTrace();
}finally {
is.close();
os.close();
}
こんな感じで書いていたが
try(FileInputStream is2 = new FileInputStream("hoge.txt");
FileOutputStream os2 = new FileOutputStream("hige.txt")){
InputStreamReader ir2 = new InputStreamReader(is2,"Shift_JIS");
OutputStreamWriter ow2 = new OutputStreamWriter(os2,"UTF-8");
int tmp;
while((tmp = ir2.read()) != -1){
ow2.write(tmp);
}
}catch (Exception e){
e.printStackTrace();
}
こう書ける
AutoCloseableを実装したクラスであれば自動でcloseしてくれる