I have the following code:
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;
}
}
Which I’m trying to test with the following code:
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() ) ) );
}
The output I would like to get is
This is the first input
This is the second input
This is the third input
This is the fourth input
but what I’m actually getting is
his is the first input
his is the first input
his is the first input
his is the first input
The problem, at least as far as I’m aware, is that the _inputStream is not being cleared in each iteration of the loop, meaning the read() function is returning immediately instead of waiting for the new stream of data. I’m resetting the stream after each reading though so I’m not sure why this should be the case.
How can I amend my code so that _inputStream.read() will wait for the user input every time the loop is run?
In the method
exec()you are calling_inputStream.read()which is blocking. But it doesn’t mean the execution goes out of exec() at this stage! This is not something like a C# coroutine.So actually
_inputStream.read()is called against whatever instance of InputStream is assigned in _inputStream elsewhere and it prints the four lines of output before you have the chance to callui.setInputStream( new ByteArrayInputStream( .....So 4 times you read in the same InputStream and you reset it after reading it. Therefore you have the same 4 lines of output.