Why am I not able to read the second line on using the second instance of Scanner? I get a "java.util.NoSuchElementException: No line found".
I understand I should use the hasNextLine() and avoided the exception, but my question is why would the second line not be available at all? Also, the reason there are multiple scanner instances is because in reality, the scanner is being instantiated in a method that is called multiple times, and I am not looking for a solution or a fix there.
Please note that I am not closing either the scanners or the streams. I am reading only 1 line each using the scanners, while I have 3 lines in the stream.
Here is my program simplified:
private void scanLines() {
String input = "Line 1." + System.lineSeparator()
+ "Line 2." + System.lineSeparator()
+ "Line 3." + System.lineSeparator();
ByteArrayInputStream bais = new ByteArrayInputStream(input.getBytes());
Scanner scanner1 = new Scanner(bais);
System.out.println(scanner1.nextLine());
Scanner scanner2 = new Scanner(bais);
System.out.println(scanner2.nextLine());
}
Output is:
Line 1.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at ScannerTest.scanLines(ScannerTest.java:23)
at ScannerTest.main(ScannerTest.java:6)