I have a problem with Scanner in Java. I have a method parsing System.in
and creating an object bases on this data. But if I create Scanner
inside the method, I have 2 ways to do that, i.e. with closing and without. In the first case, Scanner.close()
closes System.in
too, otherwise it buffers in advance and the characters it has buffered become unreachable from another Scanner.
So that now I pass a Scanner
instance into method. But it can't be reliable if you need to read from console another object e.g. via BufferedReader
. In addition, it seems not to be a really clean design solution.
Asked
Active
Viewed 144 times
0
2 Answers
0
I'm guessing the design has considered that only one Reader
or Scanner
can actually read the InputStream
(System.in
) at a time, so having several Reader
s on it is useless (as it consumes the stream as well) thus making it feasible to close the underlying InputStream
.
Edit:
One solution is to use InputStream
directly (read()
) and handle the reading of bytes yourself. For example String
has the constructor String(byte[])
that you can use together with substring()
to only return the parts that weren't used.

ddmps
- 4,350
- 1
- 19
- 34
-
Reader and Scanner aren't supposed to read the stream simultaneously but sequentially. And the reader an implementation is a detail and shoul be hidden in the implementation. Not to call close() faces us with another problem. – Evegeny Mar 25 '13 at 00:29
-
For example you pass InputStream into your method and create an instance of Scanner. But imagine you've fed the console 10 lines of text when 5 lines are sufficient to read the object properly. But when creating a new Scanner happens again the latter 5 lines aren't reachable just because the former Scanner buffered them too. And if even during destruction Scanner returns buffered lines to InputSteam, one can't rely on GC – Evegeny Mar 25 '13 at 00:30
0
Define a BufferedReader
and pass it to your methods. Use it to read lines into a String and attach a Scanner
to it instead of System.in
.

pmorken
- 764
- 4
- 11
-
The same problem occurs. If closing, stream closes too. If not, data buffered in Scanner doesn't return to the Reader – Evegeny Mar 25 '13 at 00:38
-
-
i use Scanner(System.in) because i can't predict how many symbols i shoul read – Evegeny Mar 28 '13 at 17:03