1 package org.jical; 2 3 import java.io.IOException ; 4 import java.io.InputStream ; 5 import java.io.InputStreamReader ; 6 import java.io.BufferedReader ; 7 import java.io.Reader ; 8 import java.io.UnsupportedEncodingException ; 9 import java.util.Iterator ; 10 import java.util.List ; 11 import java.util.ArrayList ; 12 13 public class LineIterator implements Iterator { 14 15 private BufferedReader m_reader; 16 private List m_lines = new ArrayList (); 17 18 public LineIterator( InputStream stream ) { 19 this( new InputStreamReader ( stream ) ); 20 } 21 public LineIterator( InputStream stream, String enc ) throws UnsupportedEncodingException { 22 this( new InputStreamReader ( stream, enc ) ); 23 } 24 public LineIterator( Reader reader ) { 25 if ( reader instanceof BufferedReader ) { 26 m_reader = (BufferedReader ) reader; 27 } else { 28 m_reader = new BufferedReader ( reader ); 29 } 30 } 31 32 public boolean hasNext() { 33 checkLines(); 34 return ( !m_lines.isEmpty() ); 35 } 36 public Object next() { 37 if ( hasNext() ) { 38 return m_lines.remove( 0 ); 39 } 40 return null; 41 } 42 public void remove() throws UnsupportedOperationException { 43 throw new UnsupportedOperationException (); 44 } 45 46 47 private void checkLines() { 48 synchronized ( m_lines ) { 49 if ( (m_lines.size()) < 1 && (m_reader != null) ) { 50 try { 51 String line = m_reader.readLine(); 52 if ( line != null ) { 53 m_lines.add( new StringBuffer ( line ) ); 54 checkLines(); 55 } else { 56 m_reader.close(); 57 m_reader = null; 58 } 59 } 60 catch ( IOException ex ) { 61 ex.printStackTrace(); 62 } 63 } 64 } 65 } 66 } 67 | Popular Tags |