IO異常處理的兩種格式

class NewIO {


public static void main(String[] args) throws Exception {
// 1.7的新特性,小括號的代碼,在小括號後的大括號的代碼執行完之後,會自動調用close()方法.
// 因爲實現了AutoCloseable接口

try (FileInputStream fis = new FileInputStream("abc.txt");
FileOutputStream fos = new FileOutputStream("bcd.txt");) {
int i;
while ((i = fis.read()) != -1)
fos.write(i);
}


// 標準的try,finally處理
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream("bcd.txt");
fis = new FileInputStream("abc.txt");
int i;
while ((i = fis.read()) != -1)
fos.write(i);
} finally {
try {
if (fis != null) {
fis.close();
}
} finally {
if (fos != null)
fos.close();
}
}
}
}
發佈了35 篇原創文章 · 獲贊 1 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章