IO异常的处理

上面两章介绍了字节流和字符流,这里总结一下IO异常的处理。

1.7前处理

格式:

try{
    //业务内容
}catch(IOException e){
    //异常处理 
}finally{
    //关流
    }

图片拷贝代码:

package IoStream;

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

public class InOutputStream {
    public static void main(String[] args){
        FileInputStream in=null;
        FileOutputStream out=null;
        try {
            //1.创建输入输出流
             in = new FileInputStream("dir/1.png");
             out = new FileOutputStream("tager/2.png");
            //2.边读边写
            byte [] buf = new byte[1024];
            int len;
            while ((len=in.read(buf))!=-1){
                out.write(buf,0,len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //3.关流
            try {
                if(out!=null)
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(in!=null)
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

代码相对比较冗余...

1.7的处理

 

jdk7中出现了一个接口叫做:AutoCloseable 无论是字节流还是字符流都实现了这个接口

格式:

try(流对象;流对象;...){
    //业务内容
    //自动关流
}catch(IOException e){
    //异常处理
}

图片拷贝代码修改:

package IoStream;

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

public class IOExcepitonTest {
    public static void main(String[] args) {

        try (//1.创建输入输出流
                FileInputStream in = new FileInputStream("dir/1.png");
                FileOutputStream out = new FileOutputStream("tager/2.png")) {
            //2.边读边写
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            //3.自动关流

        } catch (Exception e) {
            //4.异常处理
            e.printStackTrace();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值