简体   繁体   中英

Buffering with Scanner upon System.in in Java

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, ie 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 eg via BufferedReader . In addition, it seems not to be a really clean design solution.

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM