KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jical > LineIterator


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