title: Java: Stop scanner after the first token
body: <p>I try to generate automated inputs to System.in and would like to be able to read the subsequent tokens in the stream by different Scanners at arbitrary times:</p>
  
  <pre><code>// save System.in for later restoration
  InputStream inTemp = System.in;
  
  // create an input
  String input = "15 3";
  // push input into InputStream
  InputStream bais = new ByteArrayInputStream(input.getBytes());
  // deviate System.in
  System.setIn(bais);
  
  Scanner s1 = new Scanner(System.in);
  // the nextInt should only read the "15" from the input
  int i1 = s1.nextInt();
  System.out.println("#1: " + i1 * 2);
  
  Scanner s2 = new Scanner(System.in);
  // the nextInt should read the "3" from the input
  int i2 = s2.nextInt();
  System.out.println("#2: " + i2 * 2);
  
  // restore System.in
  System.setIn(inTemp);
  </code></pre>
  
  <p>Unfortunately, the Scanner s1 preventively reads the whole content of the stream instead of reading just the first token. Thus, the second Scanner s2 finds an empty input.</p>
  
  <p>The code above is an extreme simplfifcation of the real situation: The part where the Scanners are utilized is out of my responsibility. It is created by students who submit their classes to our exam-system. Our system invokes the students' methods after filling the System.in with test data. So we can not influence the way the Scanners are used. BTW: closing the Scanner won't help. The first Scanner just reads too much data from the stream.</p>
  
  <p>Actually, I see a few possible ways:</p>
  
  <ol>
  <li><p>Put markers in the input that prevent the Scanner from reading further.</p></li>
  <li><p>Extend the ByteArrayInputStream such that it reveals only one token per try. This probably means to manipulate the output of the available()-method, the pos-attribute, and the buf-contents of the Stream as well as to keep track of the number of readings performed by the Scanner. Nonetheless, the Scanner keeps asking for data, regardless of how many tokens it is supposed to read. Has anybody done that before?</p></li>
  <li><p>Use a different Stream that provides the functionality described under 2 (or something similar).</p></li>
  <li><p>Ask the students to read the data from the Scanner with a different method (instead of nextInt) that behaves as demanded. Is there such a method? I didn't find one.</p></li>
  </ol>
  
  <p>I already began to manipulate the behaviour by extending ByteArrayInputStream but didn't get too far as I was thinking this might be a conceptually too complicated approach.</p>
  
  <p>Any help is appreciated.</p>
  
  <p>Best regards,
  Thomas</p>