www.pudn.com > jnp-src.rar > LineAtATimeReader.java
/*
* Java Network Programming, Second Edition
* Merlin Hughes, Michael Shoffner, Derek Hamner
* Manning Publications Company; ISBN 188477749X
*
* http://nitric.com/jnp/
*
* Copyright (c) 1997-1999 Merlin Hughes, Michael Shoffner, Derek Hamner;
* all rights reserved; see license.txt for details.
*/
import java.io.*;
public class LineAtATimeReader extends FilterReader {
public LineAtATimeReader (Reader reader) {
super (reader);
}
protected boolean eol, eof, skipLF;
public int read () throws IOException {
synchronized (lock) {
if (eol || eof)
return -1;
int chr = in.read ();
if (skipLF && (chr == '\n'))
chr = in.read ();
skipLF = (chr == '\r');
if ((chr == '\n') || (chr == '\r')) {
eol = true;
return -1;
} else {
eof = (chr == -1);
return chr;
}
}
}
public int read (char[] data, int offset, int length) throws IOException {
if (length <= 0)
return 0;
int amount = 0;
synchronized (lock) {
int chr;
while ((amount < length) && ((chr = read ()) != -1))
data[offset + (amount ++)] = (char) chr;
}
return (amount > 0) ? amount : -1;
}
public long skip (long amount) throws IOException {
long skip = 0;
synchronized (lock) {
while ((skip < amount) && (read () != -1))
++ skip;
}
return skip;
}
protected boolean oldEOF, oldEOL, oldSkipLF;
public void mark (int readAheadLimit) throws IOException {
synchronized (lock) {
in.mark (readAheadLimit);
oldEOF = eof; oldEOL= eol; oldSkipLF = skipLF;
}
}
public void reset () throws IOException {
synchronized (lock) {
in.reset ();
eof = oldEOF; eol = oldEOL; skipLF = oldSkipLF;
}
}
public boolean nextLine () throws IOException {
synchronized (lock) {
while (read () != -1);
eol = false;
return !eof;
}
}
}