zoukankan      html  css  js  c++  java
  • java-资源管理器try-with-resource

        在java编程中会遇到很多关闭资源的问题,但是,往往我们的关闭不能百分百正确,所以java7中出现了新的资源管理器方法try-with-resource,这是一项重要的改进,因为没人能再手动关闭资源时做到100%正确,有人在想Coin项目提交这一提案时,提交者宣称jdk中有三分之二的close()用法都有bug,汗颜。

        java6资源管理器的做法,简写

    InputStream in = null;
        try{
            is = url.openStream();
            OutputStream out = new FileOutputStream(file);
            ....out.
        }catch(IOException ioe){
            // TODO: handle exception
        }finally{
            try{
                if(is != null){
                    is.close();
                }
            }catch (IOException ioe2) {
                // TODO: handle exception
            }
        }

    但是在java7中我们可以这样写

    URL url = new URL("www.baidu.com");
            try (OutputStream output = new FileOutputStream(new File("D://stest.txt"));InputStream in=url.openStream();) {
                int len;
                byte[] buffer = new byte[1024*1024*5];
                while((len = in.read(buffer)) >= 0){
                    output.write(buffer,0,len);
                }
            }

    是的非常简便,就是把资源放在try的圆括号里就可,这段代码会在资源处理完毕时,自动关闭。

    注意:

    try(ObjectInputStream obj = new ObjectInputStream(new FileInputStream("somefile.bin"))){
                ...
            }

    这里的问题是,如果从(somefile.bin)创建ObjectInputStream时出错,那么FileInputStream就不会被关闭

    最好的写法是为每个资源单独声明

    try(InputStream in = new FileInputStream("somefile.bin");
                    ObjectInputStream obj = new ObjectInputStream(in)){
                ...
            }
    如果有使用请标明来源:http://www.cnblogs.com/duwenlei/
  • 相关阅读:
    Validation failed for one or more entities
    sql 存储过程
    SQL Server分页3种方案比拼
    case when 用法
    C#如何计算代码执行时间
    透过 Jet.OLEDB 读取 Excel里面的数据
    DataBinding?资料系结?资料绑定?
    ASP.NET的OutputCache
    我想写程序#3 之 「简单地设计自己的数据表(Table)」
    我想写程序#1 之 「先确立志向」
  • 原文地址:https://www.cnblogs.com/duwenlei/p/4318874.html
Copyright © 2011-2022 走看看