jdk1.7版本起,可以自动关闭IO流

如:获取一个文件内容,以前通常是这样写:

    /**
     * 获取文件内容
     * @param file 文件
     * @return 内容
     */
    public String getText(File file){
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            byte[] b = new byte[(int) file.length()];
            fis.read(b);
            return new String(b, \"UTF-8\");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return \"\";
    }

但jdk1.7及以后就可以改写为下面格式了:把需要关闭的资源声明再try的小括号里

    /**
     * 获取文件内容
     * @param file 文件
     * @return 内容
     */
    public String getText(File file){
        try(FileInputStream fis = new FileInputStream(file)) {
            byte[] b = new byte[(int) file.length()];
            fis.read(b);
            return new String(b, \"UTF-8\");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return \"\";
    }

这样代码就节省了许多,看着也美观。

收藏 打印