用Java关闭Reader / Stream [英] Closing Reader/Stream in Java

查看:587
本文介绍了用Java关闭Reader / Stream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我必须从控制台读取用户输入:

In my code I have to read user input from console:

class Demo {
    //...some code
    public String readUserInput() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String userInput = reader.readLine();
        reader.close();
        return userInput;
    }
}

第一次使用方法 readUserInput()在Demo对象上一切正常。但是当我创建另一个Demo对象并调用方法时 - 它会抛出异常消息

On first time when I use method readUserInput() on Demo object everything is OK. But when I create another Demo object and call method - it throws Exception with the message


Stream closed

"Stream closed"

任何人都可以告诉我,为什么我在不同的不相等的对象上有异常?感谢您的关注。

Can anybody tell me, why I have Exception on different not equal objects? Thank you for your attention.

推荐答案

问题在于:

new InputStreamReader(System.in)

当你关闭你的BufferedReader,它关闭InputStreamReader,后者又关闭System.in。

When you close your BufferedReader, it closes the InputStreamReader, which in turn closes System.in.

这是 合约's .close() ,其中包含:

This is all (kind of) explained in the contract of Closeable's .close(), which says:


关闭此流并释放与之相关的任何系统资源

因此,您第二次尝试阅读你的 BufferedReader ,这最终导致数据从 System.in 中读取,但它不可用。因此你的错误。

As a result, the second time you try and read from your BufferedReader, this ultimately results in data being read from System.in, but it is unavailable. Hence your error.

更一般地说,你处理的资源很差。请阅读并学习使用try-with-resources语句。

More generally, you handle your resources poorly. Please read about, and learn to use, the try-with-resources statement.

这篇关于用Java关闭Reader / Stream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆