我有以下代码:
public class Interface {
public void exec(){
Scanner scanner = null;
Integer count = 0;
while( count < 4 ){
_inputStream.read();
scanner = new Scanner( _inputStream );
String inputLine = scanner.nextLine();
_inputStream.reset();
System.out.println( inputLine );
}
scanner.close();
}
public void setInputStream( InputStream inputStream ){
_inputStream = inputStream;
}
}
我正在尝试使用以下代码进行测试:
public void testInterface() {
Interface ui = new Interface();
ui.exec();
ui.setInputStream( new ByteArrayInputStream( "This is the first prompt".getBytes( Charset.defaultCharset() ) ) );
ui.setInputStream( new ByteArrayInputStream( "This is the second prompt".getBytes( Charset.defaultCharset() ) ) );
ui.setInputStream( new ByteArrayInputStream( "This is the third prompt".getBytes( Charset.defaultCharset() ) ) );
ui.setInputStream( new ByteArrayInputStream( "This is the fourth prompt".getBytes( Charset.defaultCharset() ) ) );
}
我想得到的输出是
This is the first input
This is the second input
This is the third input
This is the fourth input
但我实际上得到的是
his is the first input
his is the first input
his is the first input
his is the first input
至少据我所知,问题在于_inputStream
循环的每次迭代中都没有被清除,这意味着read()
函数会立即返回,而不是等待新的数据流。我在每次阅读后都会重置流,所以我不确定为什么会这样。
如何修改我的代码,以便_inputStream.read()
在每次运行循环时等待用户输入?