栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【自动关闭IO流】

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【自动关闭IO流】

自动关闭IO流,这个是java7提供的,但是有一个前提是必须实现Closeable。try段代码执行完毕后,系统会自动调用资源的关闭方法关闭资源。非常适合有些人频繁操作io可能就会忘记关闭io。

public class InputStreanDemo {
    public static void main(String[] args) {
        File file = new File("H:/test.txt");
        try(//自动关闭IO流(JAVA7)前提是必须实现Closeable
             FileInputStream fileInputStream =new FileInputStream(file);
             FileOutputStream fileOutputStream = new FileOutputStream("H:/test1.txt")
        ) {
            int len = 0;
            //read方法,若字符为文件末尾则返回值为-1
            while ((len = fileInputStream.read()) != -1) {
                fileOutputStream.write(len);
            }
        }catch (Exception e){
        }
    }
}

点进去FileInputStream 或者FileOutputStream 可以看见

FileInputStream 继承了InputStream, FileOutputStream 继承了OutputStream,继续点进去看。

里面实现了Closeable。而Closeable继承自AutoCloseable,这两个接口中只有一个方法:void close() throws Exception;

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1014748.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号