1. 程式人生 > >java的IO輸入輸出流和異常處理

java的IO輸入輸出流和異常處理

   1、不管有沒有異常,finally中的程式碼都會執行

   2、當try、catch中有return時,finally中的程式碼依然會繼續執行

   3、finally是在return後面的表示式運算之後執行的,此時並沒有返回運算之後的值,而是把值儲存起來,不管finally對該值做任何的改變,返回的值都不會改變,依然返回儲存起來的值。也就是說方法的返回值是在finally運算之前就確定了的。

   4、finally程式碼中最好不要包含return,程式會提前退出,也就是說返回的值不是try或catch中的值

io的輸入輸出流的關閉可以放在finally中

InputStream inputStream = null;
OutputStream os = null;
try {
    File file = new File(path);
 
     inputStream = new FileInputStream(new File(path));
    os = response.getOutputStream();
    byte[] b = new byte[2048];
    int length;
    while ((length = inputStream.read(b)) > 0) {
        os.write(b, 0, length);
    }

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}finally {
    // 這裡主要關閉。
    if (os != null) {
        os.close();
    }
    if (inputStream != null) {
        inputStream.close();
    }
}
return null;