从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 ""; }
原文:https://www.cnblogs.com/TinyCC/p/13065800.html