1. 程式人生 > >Java基礎---IO異常處理

Java基礎---IO異常處理

package cn.itcast.exception;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;


/*
 IO異常處理
 
 
 */
public class Demo1 {


public static void main(String[] args) {
readTest();
copyImage();


}
//需求:把拷貝圖片的處理異常的程式碼寫下
public static void copyImage(){
// 找到目標檔案
File inFile = new File("F:\\1.jpg");
File destFile = new File("E:\\1.jpg");

//建立資料的輸入輸出通道
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(inFile);

//每次建立一個FileOutputStream的時候,預設情況下FileOutputStream的指標是指向了檔案的開始位置。每寫出一次,指向都會出現相應移動
fileOutputStream = new FileOutputStream(destFile);
//建立緩衝資料邊讀邊寫
byte[] buf = new byte[1024];
int length = 0;
while((length = fileInputStream.read(buf))!=-1){//最後一次只剩下了824個位元組
fileOutputStream.write(buf, 0, length);
}
} catch (IOException e) {
System.out.println("拷貝圖片出錯");
throw new RuntimeException(e);
}finally{
//關閉資源原則:先開後關,後開先關。
try{
if(fileOutputStream!=null){

fileOutputStream.close();
}
}catch(IOException e){
System.out.println("關閉輸入資源失敗。。");
throw new RuntimeException(e);
}finally{
try{
if(fileInputStream!=null){

fileInputStream.close();
}
}catch(IOException e){
System.out.println("關閉輸入資源失敗。。");
throw new RuntimeException(e);
}

}
}
}
public static void readTest() {
FileInputStream fileInputStream = null;
try{
//找到目標檔案
File file = new File("F:\\a.txt");
//建立資料輸入通道
fileInputStream = new FileInputStream(file);

//建立緩衝陣列讀取資料
byte[] buf = new byte[1024];
int length = 0;
while((length = fileInputStream.read())!=-1){
System.out.println(new String(buf,0,length));
     }
} catch (IOException e) {
/*
//處理程式碼...首先要阻止後面的程式碼執行,而且要需要通知呼叫者這裡出錯了。。。
throw new RuntimeException(e);//把IOException傳遞給RuntimeException包裝一層,然後再丟擲,這樣子做的目的是為了讓呼叫者使用變得靈活
*/
System.out.println("讀取檔案資源出錯。。。");
throw new RuntimeException(e);
}finally{
try {
if(fileInputStream!=null){
fileInputStream.close();
System.out.println("關閉資源成功了");
}
} catch (IOException e) {
System.out.println("關閉資源失敗了;");
throw new RuntimeException(e);

  }
   }
}


}