java学习笔记--io流的异常处理

本文通过一个Java示例程序介绍了如何使用IO流完成图片的复制操作,并详细解释了程序中可能出现的异常处理方式,包括文件读写及资源关闭过程。
public static void main(String[] args) {
    //  readTest();

        copyImage();
    }

    // 拷贝图片
    public static void copyImage() {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            // 找到目标文件
            File inFile = new File("F:\\美女\\1.jpg");
            File outFile = new File("E:\\1.jpg");
            // 建立输入输出通道
            fileInputStream = new FileInputStream(inFile);
            fileOutputStream = new FileOutputStream(outFile);
            // 建立缓冲数组,边读边写
            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("拷贝图片出错...");
            throw new RuntimeException(e);//读取的错误
        } finally {
            // 关闭资源
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                    System.out.println("关闭输出流对象成功...");
                }
            } catch (IOException e) {//关闭的错误
                System.out.println("关闭输出流资源失败...");
                throw new RuntimeException(e);
            } finally {
                if (fileInputStream != null) {
                    try {
                        fileInputStream.close();
                        System.out.println("关闭输入流对象成功...");
                    } catch (IOException e) {
                        System.out.println("关闭输入流对象失败...");
                        throw new RuntimeException(e);
                    }
                }

            }
        }
    }

总结:io流抛出异常的位置有两个
1. 打开的文件的时候 文件损坏或者硬盘损坏等
主要是 抛出包装后的错误信息RuntimeException(e)
2. 流关闭放在finally中 但是关闭流的时候也会发生错误
3. 如果io流抛出异常 就无法执行接下里的任务 所以我们要try{} catch(){}finally{}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值