スッキリ分かるJava入門 実践編9章の章末問題の解答に記載されているコードですが、
ファイルを閉じるtry-catch文がfinallyで囲まれていません。
closeは必ずfinallyで閉じなければならないと同シリーズ入門編で書かれていたのですが、
なぜこのコードの場合はfinallyをつける必要がないのでしょうか?
Java
1import java.io.*; 2import java.util.zip.GZIPOutputStream.*; 3 4public class Main { 5 public static void main(String[] args) { 6 String inFile = args[0]; 7 String outFile = args[1]; 8 FileInputStream fis = null; 9 GZIPOutputStream gzos = null; 10 11 try { 12 fis = new FileInputStream(inFile); 13 FileOutputStream fos = new FileOutputStream(outFile); 14 BufferedOutputStream bos = new BufferedOutputStream(fos); 15 gzos = new GZIPOutputStream(bos); 16 int i = fis.read(); 17 while(i != -1) { 18 gzos.write(i); 19 i = fis.read(); 20 } 21 gzos.flush(); 22 gzos.close(); 23 fis.close(); 24 } catch (IOException e) { 25 System.out.println("ファイル操作に失敗しました"); 26 try { 27 if(fis != null) { 28 fis.close(); 29 } 30 if(gzos != null) { 31 gzos.close(); 32 } 33 } catch (IOException ee) { } 34 } 35 } 36}
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/05/12 09:34