1    package com.instantbank.collections.util;
2    
3    import java.util.Iterator;
4    import java.util.LinkedList;
5    import java.util.List;
6    
7    public class FuzzyLineReader {
8    
9      private String data;
10     private int pointer, lineSize, len;
11     private boolean atEnd;
12   
13   
14     public FuzzyLineReader(String theData, int theSize) {
15       data = theData;
16       lineSize = theSize;
17       len = data.length();  // Determine this once
18       pointer = 0;
19       atEnd = false;
20     }
21   
22   
23     public String getNextLine() {
24       if(atEnd) {
25         return null;
26       }
27   
28       String result = "";
29   
30       // If the end of this line is not a space, back up until we reach one.
31       // We always return with the last character being a space
32   
33       int start = pointer;
34       int end = pointer + lineSize;
35       if(end >= len) {
36         end = len;
37         atEnd = true;
38       }
39       else {
40         // 11192002 tjm - Error when a word is >40 characters (e.g. '*****')
41         //                Back up a max of 20 characters, then return what we have
42         int max = 0;
43         while(data.charAt(end) != ' ' && end >= 0 && max <= 20) {
44           max++;
45           end--;
46         }
47         if(max >= 20) {
48           end = pointer + lineSize;  // Show as much as we can for this line
49         }
50         else {
51           end++;
52         }  // skip the space
53       }
54   
55       result = data.substring(start, end);
56   
57       pointer = end;
58   
59       return result;
60     }
61   
62   
63     public List getAllLines() {
64       LinkedList list = new LinkedList();
65   
66       String line;
67       while((line = getNextLine()) != null) {
68         list.add(line);
69       }
70   
71       return list;
72     }
73   
74   
75     public static void main(String[] args) {
76       FuzzyLineReader reader = new FuzzyLineReader(
77         "This ", 25);
78       for(Iterator walker = reader.getAllLines().iterator(); walker.hasNext(); ) {
79         String s = (String)walker.next();
80         System.out.println("Line='" + s + "'");
81       }
82     }
83   
84   }
85