java.util.Scanner second instance throwing NoSuchElementException -


this question has answer here:

why not able read second line on using second instance of scanner? "java.util.nosuchelementexception: no line found".

i understand should use hasnextline() , avoided exception, question why second line not available @ all? also, reason there multiple scanner instances because in reality, scanner being instantiated in method called multiple times, , not looking solution or fix there.

please note not closing either scanners or streams. reading 1 line each using scanners, while have 3 lines in stream.

here 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         @ java.util.scanner.nextline(unknown source)         @ scannertest.scanlines(scannertest.java:23)         @ scannertest.main(scannertest.java:6) 

use multiple scanners (on same stream) bad practice, because scanners consume stream share.

this cause of exception java.util.nosuchelementexception: no line found had.

i've tested code , exception raised second nextline() invocation.

into each scanner class saved reference same input stream.

when scanner1.nextline() method invoked, read bunch of bytes on stream , position moved ahead.

just clear, i've double checked debugging source code of scanner class.

when nextline() method called, behind scenes stream moved ahead of 1024 position copying result buffer

// internal buffer used hold input private charbuffer buf; 

try debug java source code , @ method readinput().


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -