01: /*
02: * @(#)LineInputStream.java 1.2 04/12/06
03: *
04: * Copyright (c) 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.nio;
10:
11: import org.pnuts.text.*;
12: import java.io.*;
13:
14: /**
15: * This class is used to read lines from a character stream.
16: */
17: public class LineInputStream extends AbstractLineInputStream {
18:
19: protected LineHandler handler;
20: protected InputStream input;
21: protected boolean needToClose;
22:
23: public LineInputStream(InputStream input, LineHandler handler,
24: boolean needToClose) {
25: this (input, defaultBufferSize, handler, needToClose);
26: }
27:
28: public LineInputStream(InputStream input, int sz,
29: LineHandler handler, boolean needToClose) {
30: super (sz);
31: this .input = input;
32: this .handler = handler;
33: this .needToClose = needToClose;
34: }
35:
36: /**
37: * Fills the buffer.
38: * This method is called when LineInputStream needs more data.
39: */
40: protected int fill(byte[] b, int offset, int size)
41: throws IOException {
42: return input.read(b, offset, size);
43: }
44:
45: /**
46: * Process a line.
47: *
48: * @param c the char buffer that contains the current line.
49: * @param offset the offset of the buffer
50: * @param length the length of the current line
51: */
52: protected void process(byte[] b, int offset, int length) {
53: handler.process(b, offset, length);
54: }
55:
56: /**
57: * Process all lines.
58: *
59: * @param includeNewLine if true newline code (\r|\n|\r\n) is appended.
60: * @return the number of lines processed
61: */
62: public int processAll(boolean includeNewLine) throws IOException {
63: int count = 0;
64: try {
65: while (!stopped && processLine(includeNewLine)) {
66: count++;
67: }
68: return count;
69: } finally {
70: if (needToClose) {
71: input.close();
72: }
73: }
74: }
75: }
|