关闭流的方法

一、自己写一个工具类关闭

可变参数:...三个点,只能放在形参的最后一个位置。表示可以传递任意个参数,处理方式同数组。
程序

public static void close(Closeable... io) {
        for (Closeable temp : io) {
            if (temp != null) {
                try {
                    temp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static <T extends Closeable> void closeAll(T... io) {

        for (Closeable temp : io) {
            if (temp != null) {
                try {
                    temp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

<br />
二、1.7新增方法,try-with-resource
程序

public static void read(String srcPath) {

        File src = new File(srcPath);
        try (
                ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(new FileInputStream(src)));
            ) 
            {
                Object o1 = ois.readObject();
                Object o2 = ois.readObject();
                if (o1 instanceof Employee) {
                    Employee e1 = (Employee) o1;
                    System.out.println(e1.getSalary());
                    System.out.println(e1.getName());
                }
                if (o2 instanceof Employee) {
                    Employee e2 = (Employee) o2;
                    System.out.println(e2.getSalary());
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
        }

    }

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,281评论 19 139
  • 前言 把《C++ Primer》[https://book.douban.com/subject/25708312...
    尤汐Yogy阅读 9,555评论 1 51
  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,866评论 0 4
  • 前段时间有位和我一起学习的同学问我“如何学习搞定一门课程?”我在想我们一直在讨论学习、学习知识、学习技能、学习使用...
    李鑫原创阅读 364评论 2 6
  • 3月3日是我的阴历生日,那两天因为忙着为进修校来听课做准备,早把生日的事忘到了脑后。 中午下班,坐在校车上,翻了一...
    墨香悠然666阅读 440评论 5 5