好的,这可能不是最好的问题,但我坚持下去,无法在网上找到答案。
此代码第二次不会从标准输入中读取:
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)))
{
input = br.readLine();
}
catch (final Exception e)
{
System.err.println("Read from STDIN failed: " + e.getMessage());
}
// do some processing
try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in)))
{
input = br.readLine();
}
catch (final Exception e)
{
System.err.println("Read from STDIN failed: " + e.getMessage());
}
我知道 java 的 try-with-resources 会递归地关闭链中的所有流,所以在第一次读取后System.in
关闭。有什么好的解决方法吗?或者我真的应该处理关闭自己的流吗?
upd: 我试图处理关闭自己的流(即 java6 风格)。如果有人感兴趣,这是一个代码。但我注意到,这种闭链行为不是来自 try-with-resources bur,而是来自 close-methods 的实现。所以我没有从那次尝试中赢得任何东西。
我选择 fge 的解决方案是因为它是最冗长的解决方案。它直接对我有用。
总而言之,这对我来说似乎很奇怪,java没有开箱即用的解决方案,因为存在不应该关闭的系统流。