一般在操作IO時(shí)異常的處理原則
package cn.itcast.exception;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.management.RuntimeErrorException;
/*
IO異常應(yīng)該如何處理:
*/
public class Demo1 {
public static void main(String[] args) {
readTest();
}
//拷貝圖片
public static void copyImage(){
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try{
//找到目標(biāo)文件
File inFile = new File("F:\\美女\\1.jpg");
File outFile = new File("F:\\拷貝.jpg");
//建立數(shù)據(jù)的輸入輸出通道
fileInputStream = new FileInputStream(inFile);
fileOutputStream = new FileOutputStream(outFile);
//建立緩沖字節(jié)數(shù)組猫态,邊讀邊寫(xiě)
byte[] buf = new byte[1024];
int length = 0 ;
while((length = fileInputStream.read(buf))!=-1){
fileOutputStream.write(buf,0,length);
}
}catch(IOException e){
System.out.println("拷貝出錯(cuò)了...");
throw new RuntimeException(e);
//關(guān)閉資源的原則: 先開(kāi)后關(guān), 后開(kāi)先關(guān)遭庶。
}finally{
try{
if(fileOutputStream!=null){
//關(guān)閉資源
fileOutputStream.close();
}
}catch(IOException e){
throw new RuntimeException(e);
}finally{
try{
if(fileInputStream!=null){
fileInputStream.close();
}
}catch(IOException e){
throw new RuntimeException(e);
}
}
}
}
public static void readTest() {
FileInputStream fileInputStream = null;
try{
File file = new File("F:\\a.txt");
//建立文件的輸入流通道
fileInputStream = new FileInputStream(file);
//建立緩沖字節(jié)數(shù)組讀取文件數(shù)據(jù)
byte[] buf = new byte[1024];
int length = 0 ; //記錄本次讀取的字節(jié)個(gè)數(shù)
//讀取文件的數(shù)據(jù)
while((length = fileInputStream.read(buf))!=-1){
System.out.println(new String(buf,0,length));
}
}catch(IOException e){
//如何處理???
System.out.println("讀取文件出錯(cuò)...");
throw new RuntimeException(e); // 把真正的異常原因包裝到RuntimeException中然后再拋出慎菲。 (糖衣炮彈)
}finally{
try{
//關(guān)閉資源()
if(fileInputStream!=null){
fileInputStream.close();
System.out.println("關(guān)閉資源成功...");
}
}catch(IOException e){
System.out.println("關(guān)閉資源失敗...");
throw new RuntimeException(e);
}
}
}
}