public static Iterator < String > iterator ( Reader self ) { final BufferedReader bufferedReader ; if ( self instanceof BufferedReader ) bufferedReader = ( BufferedReader ) self ; else bufferedReader = new BufferedReader ( self ) ; return new Iterator < String > ( ) { String nextVal /* = null */ ; boolean nextMustRead = true ; boolean hasNext = true ; public boolean hasNext ( ) { if ( nextMustRead && hasNext ) { try { nextVal = readNext ( ) ; nextMustRead = false ; } catch ( IOException e ) { hasNext = false ; } } return hasNext ; } public String next ( ) { String retval = null ; if ( nextMustRead ) { try { retval = readNext ( ) ; } catch ( IOException e ) { hasNext = false ; } } else retval = nextVal ; nextMustRead = true ; return retval ; } private String readNext ( ) throws IOException { String nv = bufferedReader . readLine ( ) ; if ( nv == null ) hasNext = false ; return nv ; } public void remove ( ) { throw new UnsupportedOperationException ( "Cannot remove() from a Reader Iterator" ) ; } } ; }
Creates an iterator which will traverse through the reader a line at a time .