Ok, here is a probably not the best question, but I'm stuck with it and can't find answer to this on the net.
This code won't read from standard input the second time:
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());
}
I know java's try-with-resources recursively closes all streams in the chain, so after the first reading System.in
is closed. Is there any good workaround for that? Or should I really handle stream closing myself?
upd: I tried to handle the stream closing myself (that is java6-style). Here's a code if somebody's interested. But I noticed that this chain-closing behaviour comes not from try-with-resources bur rather from the implementation of close-methods. So I didn't win anything from that attempt.
I pick fge's solution because it's the most verbose one. It worked for me directly.
All in all it seems quite strange to me, that java doesn't have such solution out of the box since there are system streams which shouldn't be closed.