KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jical > UnfoldingLineIterator


1 package org.jical;
2
3 /*
4  * Never used..
5 import java.io.IOException;
6 import java.io.InputStream;
7 import java.io.InputStreamReader;
8 import java.io.BufferedReader;
9 import java.io.UnsupportedEncodingException;
10 */

11 import java.io.Reader JavaDoc;
12 import java.util.Iterator JavaDoc;
13 import java.util.List JavaDoc;
14 import java.util.ArrayList JavaDoc;
15
16 public class UnfoldingLineIterator implements Iterator JavaDoc {
17
18     private Iterator JavaDoc m_iterator;
19     private List JavaDoc m_lines = new ArrayList JavaDoc();
20
21     public UnfoldingLineIterator( Reader JavaDoc reader ) {
22         this( new LineIterator( reader ) );
23     }
24     public UnfoldingLineIterator( Iterator JavaDoc iterator ) {
25         m_iterator = iterator;
26     }
27
28     public boolean hasNext() {
29         checkLines();
30         return ( !m_lines.isEmpty() );
31     }
32     public Object JavaDoc next() {
33         if ( hasNext() ) {
34             return m_lines.remove( 0 );
35         }
36         return null;
37     }
38     public void remove() throws UnsupportedOperationException JavaDoc {
39         throw new UnsupportedOperationException JavaDoc();
40     }
41
42
43     
44     private void checkLines() {
45         synchronized ( m_lines ) {
46             if ( m_lines.size() < 2 && m_iterator.hasNext() ) {
47                 StringBuffer JavaDoc line = (StringBuffer JavaDoc) m_iterator.next();
48                 if ( line != null ) {
49                     m_lines.add( line );
50                     unfoldLines();
51                     checkLines();
52                 }
53             }
54         }
55     }
56     
57     private void unfoldLines() {
58         synchronized ( m_lines ) {
59             int i = 1;
60             while ( i < m_lines.size() ) {
61                 StringBuffer JavaDoc line = (StringBuffer JavaDoc) m_lines.get( i );
62                 char c = line.charAt( 0 );
63                 if ( c == ' ' || c == '\t' ) {
64                     m_lines.remove( i );
65                     StringBuffer JavaDoc pline = (StringBuffer JavaDoc) m_lines.get( i - 1 );
66                     line.deleteCharAt( 0 );
67                     pline.append( line );
68                 } else {
69                     i++;
70                 }
71             }
72         }
73     }
74
75     
76 }
77
Popular Tags