简体   繁体   English

使用Java中的System.in在Scanner上进行缓冲

[英]Buffering with Scanner upon System.in in Java

I have a problem with Scanner in Java. 我在Java中使用扫描仪时遇到问题。 I have a method parsing System.in and creating an object bases on this data. 我有一个解析System.in并基于此数据创建对象的方法。 But if I create Scanner inside the method, I have 2 ways to do that, ie with closing and without. 但是,如果我在方法内部创建Scanner ,则有2种方法可以做到这一点,即关闭和不关闭。 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. 在第一种情况下, Scanner.close()关闭System.in ,否则它将预先缓冲,并且其缓冲的字符将无法从另一个Scanner访问。 So that now I pass a Scanner instance into method. 因此,现在我将Scanner实例传递给方法。 But it can't be reliable if you need to read from console another object eg via BufferedReader . 但是,如果您需要从控制台读取另一个对象(例如,通过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 . 我猜想该设计考虑到一次只能Reader一个ReaderScanner实际上一次读取InputStreamSystem.in ),因此在上面具有多个Reader是没有用的(因为它也会消耗流),因此使其可行关闭基础InputStream

Edit: One solution is to use InputStream directly ( read() ) and handle the reading of bytes yourself. 编辑:一种解决方案是直接使用InputStreamread() )并自行处理字节读取。 For example String has the constructor String(byte[]) that you can use together with substring() to only return the parts that weren't used. 例如, String具有构造函数String(byte[]) ,您可以将其与substring()一起使用,以仅返回未使用的部分。

Define a BufferedReader and pass it to your methods. 定义一个BufferedReader并将其传递给您的方法。 Use it to read lines into a String and attach a Scanner to it instead of System.in . 使用它可以将行读入字符串中,并在其上附加一个Scanner而不是System.in

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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