自动关闭IO流

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

把需要关闭的资源声明再try的小括号里即可省略之后的close(),简洁美观省力。

/**
* 获取文件内容
* @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 "";
}

 

posted @ 2020-06-08 15:10  Tiny_Cc  阅读(510)  评论(0)    收藏  举报