01: /*
02: * MailReader.java
03: *
04: * Copyright (C) 2002 Peter Graves
05: * $Id: MailReader.java,v 1.1.1.1 2002/09/24 16:09:53 piso Exp $
06: *
07: * This program is free software; you can redistribute it and/or
08: * modify it under the terms of the GNU General Public License
09: * as published by the Free Software Foundation; either version 2
10: * of the License, or (at your option) any later version.
11: *
12: * This program is distributed in the hope that it will be useful,
13: * but WITHOUT ANY WARRANTY; without even the implied warranty of
14: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15: * GNU General Public License for more details.
16: *
17: * You should have received a copy of the GNU General Public License
18: * along with this program; if not, write to the Free Software
19: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20: */
21:
22: package org.armedbear.j.mail;
23:
24: import java.io.IOException;
25: import java.io.InputStream;
26:
27: public final class MailReader {
28: private final InputStream inputStream;
29:
30: private byte[] buf = new byte[16384];
31: private int count;
32: private int pos;
33: private char[] chars = new char[1024];
34: private long offset;
35:
36: public MailReader(InputStream inputStream) {
37: this .inputStream = inputStream;
38: }
39:
40: public final long getOffset() {
41: return offset;
42: }
43:
44: public String readLine() throws IOException {
45: int i = 0;
46: while (true) {
47: if (pos >= count) {
48: fill();
49: if (pos >= count) {
50: // End of stream.
51: if (i > 0)
52: return new String(chars, 0, i);
53: else
54: return null;
55: }
56: }
57: byte b = buf[pos++];
58: if (b == 10) {
59: // End of line.
60: ++offset;
61: return new String(chars, 0, i);
62: } else if (b == 13) {
63: // Ignore.
64: ++offset;
65: } else {
66: if (i == chars.length) {
67: // Need to grow char array.
68: char[] newChars = new char[chars.length * 2];
69: System.arraycopy(chars, 0, newChars, 0,
70: chars.length);
71: chars = newChars;
72: }
73: ++offset;
74: chars[i++] = (char) (b & 0xff);
75: }
76: }
77: }
78:
79: public void close() throws IOException {
80: inputStream.close();
81: }
82:
83: private final void fill() throws IOException {
84: pos = 0;
85: count = inputStream.read(buf);
86: }
87: }
|