1 import java.io.BufferedReader;
2 import java.io.FileNotFoundException;
3 import java.io.IOException;
4 import java.io.StringReader;
7 * A file reader that concatenates lines
12 public class BufferedLineReader
16 String cleanLine(String l);
20 * a reader for the file being read
22 private BufferedReader br;
25 * optional handler to post-process each line as it is read
27 private LineCleaner cleaner;
30 * current buffer of <bufferSize> post-processed input lines
32 private String[] buffer;
34 private boolean atEof;
41 * the number of lines to concatenate at a time while reading
43 * an optional callback handler to post-process each line after
45 * @throws FileNotFoundException
47 public BufferedLineReader(BufferedReader reader, int bufferSize,
52 buffer = new String[bufferSize];
56 * load up the buffer with N-1 lines, ready for the first read
58 for (int i = 1; i < bufferSize; i++)
66 * Reads the next line from file, invokes the post-processor if one was
67 * provided, and returns the 'cleaned' line, or null at end of file.
71 private String readLine() // throws IOException
82 } catch (IOException e)
93 line = cleaner.cleanLine(line);
97 * shuffle down the lines buffer and add the new line
98 * in the last position
100 for (int i = 1; i < buffer.length; i++)
102 buffer[i - 1] = buffer[i];
104 buffer[buffer.length - 1] = line;
109 * Returns a number of concatenated lines from the file, or null at end of
116 if (readLine() == null)
120 StringBuilder result = new StringBuilder(100 * buffer.length);
121 for (String line : buffer)
128 return result.toString();
132 * A main 'test' method!
134 * @throws IOException
136 public static void main(String[] args) throws IOException
138 String data = "Now is the winter\n" + "Of our discontent\n"
139 + "Made glorious summer\n" + "By this sun of York\n";
140 BufferedReader br = new BufferedReader(new StringReader(data));
141 BufferedLineReader reader = new BufferedLineReader(br, 3,
145 public String cleanLine(String l)
147 return l.toUpperCase();
150 String line = reader.read();
151 String expect = "NOW IS THE WINTEROF OUR DISCONTENTMADE GLORIOUS SUMMER";
152 if (!line.equals(expect))
154 System.err.println("Fail: expected '" + expect + "', found '" + line
159 System.out.println("Line one ok!");
161 line = reader.read();
162 expect = "OF OUR DISCONTENTMADE GLORIOUS SUMMERBY THIS SUN OF YORK";
163 if (!line.equals(expect))
165 System.err.println("Fail: expected '" + expect + "', found '" + line
170 System.out.println("Line two ok!!");
172 line = reader.read();
175 System.err.println("Fail: expected null at eof, got '" + line + "'");
179 System.out.println("EOF ok!!!");