流的標準異常處理jdk1.6版本及其以前
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("aaa.txt");
fos = new FileOutputStream("bbb.txt");
int b;
while((b = fis.read()) != -1) {
fos.write(b);
}
} finally {
try {
if(fis != null)
fis.close();
}finally {
if(fos != null)
fos.close();
}
}
流的標準異常處理jdk1.7版本
try(
FileInputStream fis = new FileInputStream("aaa.txt");
FileOutputStream fos = new FileOutputStream("bbb.txt");
){
int b;
while((b = fis.read()) != -1) {
fos.write(b);
}
}
原理:在try()中創建的流對象必須實現AutoCloseable接口,如果實現了,在try後面的{}(讀寫代碼)執行後就會自動調用流對象的close方法將流關掉