【发布时间】:2018-04-10 08:12:45
【问题描述】:
这是我的问题。我用从用户键盘获取原始值的方法制作了简单的输入类。问题是,每当我在其他类中使用这个类时,我都会遇到一个问题,即当我创建多个实例时在这个课程中,我遇到了“关闭流”的问题。为什么会发生这种情况?
例如:我有一个主要方法,我在其中获取用户的输入并决定制作哪个对象,比如说我可以制作 4 个不同的对象(4 个类),在我调用对象“设置状态”方法之后,我实际设置的位置这个对象的所有状态都创建了输入类的第二个实例,然后,当我尝试在我的主方法中再次读取用户的输入时,我得到一个异常“流关闭”。 这是输入类的代码:
public class UserInput {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));;
public int getInt() {
try {
String line;
line = reader.readLine();
return Integer.parseInt(line);
} catch (Exception ex) {
ex.printStackTrace();
return -1;
}
}
public double getDouble() {
try {
String line = reader.readLine();
return Double.parseDouble(line);
} catch (Exception ex) {
return -1;
}
}
public float getFloat() {
try {
String line = reader.readLine();
return Float.parseFloat(line);
} catch (Exception ex) {
return -1;
}
}
public long getLong() {
try {
String line = reader.readLine();
return Long.parseLong(line);
} catch (Exception ex) {
return -1;
}
}
public short getShort() {
try {
String line = reader.readLine();
return Short.parseShort(line);
} catch (Exception ex) {
return -1;
}
}
public String getString() {
try {
String line = reader.readLine();
return line;
} catch (Exception ex) {
return " ";
}
}
public char getChar() {
try {
return (char) reader.read();
} catch (Exception ex) {
return (' ');
}
}
public void close() {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
【问题讨论】:
-
“为什么会这样?”您没有使用此类显示代码,但我想这是因为您正在调用
close()方法。一般的经验法则是不要关闭您没有打开的流;而你没有打开System.in。 -
您关闭的阅读器关闭底层流,在您的情况下为
System.in。一旦关闭,您将无法重新打开它。 -
非常感谢,现在我明白了。有什么方法可以在不关闭 System.in 的情况下关闭 BufferedReader 吗?