jdk1.7新特性之 try-with-resources

在早前一段时间接触到这个特性,当时以为没什么大不了的(主要是当时不了解),多是本身当初看的时候没辣么仔细吧!哈哈,如今从新接触感受挺不错的,特此记录下来java

在java6以前咱们的资源管理语法模式大概是这样的:.net

        byte[] buf = new byte[1024];
        FileInputStream fin = null;
        FileOutputStream fout = null;
        try {
            //资源操做
            fin = new FileInputStream(args[0]);
            fout = new FileOutputStream(args[1]);
            int i = fin.read(buf, 0, 1024);
            while(i != -1) {
                fout.write(buf, 0, i);
                i = fin.read(buf, 0, 1024);
            }
        } catch (Exception e) {
            //异常处理
            e.printStackTrace();
        } finally {
            //资源释放
            try {
                fin.close();
                fout.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

如今在java7中,咱们能够这样写了:code

        byte[] buf = new byte[1024];
        try (FileInputStream fin = new FileInputStream(args[0]);
            FileOutputStream fout = new FileOutputStream(args[1])
                ){
            //异常处理
            int i = fin.read(buf, 0, 1024);
            while(i != -1) {
                fout.write(buf, 0, i);
                i = fin.read(buf, 0, 1024);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

看了上面的代码会不会觉的很清晰,也以为很cool,反正我是以为很cool了。  
接口

在java7中,放在try括号里的资源会在try执行完毕后自动关闭,这样减小了咱们编写错误代码的概率了,由于咱们在处理资源的时候不免发生错误。并且资源的各类组合错误很让人头疼的。不过,使用这个新特性的时候有几点要注意:资源

1. 在TWR的try从句中的出现的资源必须实现AutoCloseable接口的, 在java7中,大多数资源都被修改过了,能够放心使用it

2. 在某些状况下资源可能没法关闭,好比io

FileReader reader = new FileReader(new File("c:\\test.txt"));

当new File出错时,FileReader就可能关闭不了,因此正确的作法是为各个资源声明独立变量class

最后,推荐一篇博文 http://www.oschina.net/question/12_10706,也是讲这个新特性的test

相关文章
相关标签/搜索