看来直觉是对的,br.close效果已经包含了System.in.close(); 流的close无法改变只初始化一次的本质,因为System.in是final的 /** * The "standard" input stream. This stream is already * open and ready to supply input data. Typically this stream * corresponds to keyboard input or another input source specified by * the host environment or user. */ public final static InputStream in = nullInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("第一个BR,请输入测试数据:");
String str = br.readLine();
System.out.println(str);System.out.println("第二个BR,请输入测试数据:");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
str = br1.readLine();
System.out.println(str);
br1.close();以上代码定义了两个br,每个br用完立即关闭。按照楼上有人说的,第二个br岂不有问题?
但运行过的人会知道,每个br都可以正常运行。
综述,lz的问题不在于System.in这个流被关了,而是你频繁的创建BR,而关闭只做了一次(就是你最后创建的那个br)。如果你一次while后立即关闭这个br,问题就不存在了
同意此楼的差点,每一次while中,br都应该关闭一次,你再加行关闭代码 试试
br = new BufferedReader(new InputStreamReader(System.in));
因为即使关闭System.in流,问题依旧try {
System.in.close();
br.close();
} catch(Exception e) {
e.printStackTrace();
}纳闷引用已经指向新的对象了,之前的操作居然还会对其产生影响,这个BufferedInputStream很奇怪又不见有初始化内部属性buf[]的过程
* The "standard" input stream. This stream is already
* open and ready to supply input data. Typically this stream
* corresponds to keyboard input or another input source specified by
* the host environment or user.
*/
public final static InputStream in = nullInputStream();
您觉得怎样才是在while里面关闭br哦,貌似那个finally {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}都在while里面吧!
你的代码里只有一次close啊,哪有每次都关闭br
如果br关闭了,里面的流会随之关闭的,看一下close方法的实现就清楚了。
system.in没必要每次关闭。
System.out.println("第一个BR,请输入测试数据:");
String str = br.readLine();
System.out.println(str);
br.close();System.out.println("第二个BR,请输入测试数据:");
BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
str = br1.readLine();
System.out.println(str);
br1.close();运行如上代码,到br1的时候则会抛出Stream Closed的异常。