01: /*
02: * @(#)LineReader.java 1.2 04/12/06
03: *
04: * Copyright (c) 2001-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.text;
10:
11: import java.io.*;
12:
13: /**
14: * This class is used to read lines from a character stream.
15: * Unlike BufferedReader.readLine(), this class allows you to
16: * process lines without instantiating a String object for each
17: * line.
18: */
19: public class LineReader extends AbstractLineReader {
20:
21: protected LineHandler handler;
22: protected Reader input;
23: protected boolean needToClose;
24:
25: public LineReader(Reader input, int sz, LineHandler handler,
26: boolean needToClose) {
27: super (sz);
28: this .input = input;
29: this .handler = handler;
30: this .needToClose = needToClose;
31: }
32:
33: public LineReader(Reader input, LineHandler handler,
34: boolean needToClose) {
35: this (input, defaultCharBufferSize, handler, needToClose);
36: }
37:
38: /**
39: * Fills the buffer.
40: * This method is called when LineReader needs more data.
41: */
42: protected int fill(char[] c, int offset, int size)
43: throws IOException {
44: return input.read(c, offset, size);
45: }
46:
47: /**
48: * Process a line.
49: *
50: * @param c the char buffer that contains the current line.
51: * @param offset the offset of the buffer
52: * @param length the length of the current line
53: */
54: protected void process(char[] c, int offset, int length) {
55: handler.process(c, offset, length);
56: }
57:
58: /**
59: * Process all lines.
60: *
61: * @param includeNewLine if true newline code (\r|\n|\r\n) is appended.
62: * @return the number of lines processed
63: */
64: public int processAll(boolean includeNewLine) throws IOException {
65: int count = 0;
66: try {
67: while (!stopped && processLine(includeNewLine)) {
68: count++;
69: }
70: return count;
71: } finally {
72: if (needToClose) {
73: input.close();
74: }
75: }
76: }
77: }
|