Java基础---IO异常处理

来源:互联网 发布:ospf spf算法 编辑:程序博客网 时间:2024/05/20 19:33
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);

  }
   }
}


}
原创粉丝点击