用于判断字符结尾的输入流类

    技术2022-05-11  27

    import java.io.IOException;import java.io.InputStream;

    public class CharTerminatedInputStream extends InputStream {

      private InputStream in;

      private int match[];

      private int buffer[];

      private int pos = 0;

      private boolean endFound = false;

      public CharTerminatedInputStream(InputStream in, byte[] terminator) {    if (terminator == null) {      throw new IllegalArgumentException("The terminating character array cannot be null.");    }    if (terminator.length == 0) {      throw new IllegalArgumentException("The terminating character array cannot be of zero length.");    }    match = new int[terminator.length];    buffer = new int[terminator.length];    for (int i = 0; i < terminator.length; i++) {      match[i] = (int) terminator[i];      buffer[i] = (int) terminator[i];    }    this.in = in;  }

      public synchronized void reset() {    endFound = false;    pos = 0;  }

      public int read() throws IOException {

        if (endFound) {      return -1;    }

        if (pos == 0) {      int b = in.read();      if (b == -1) {        endFound = true;        return -1;      }      if (b != match[0]) {        return b;      }      buffer[0] = b;      pos++;    } else {      if (buffer[0] != match[0]) {        return topChar();      }    }    for (int i = 0; i < match.length; i++) {      if (i >= pos) {        int b = in.read();        if (b == -1) {          return topChar();        }        buffer[pos] = b;        pos++;      }      if (buffer[i] != match[i]) {        return topChar();      }    }    endFound = true;    return -1;  }

      private int topChar() {    int b = buffer[0];    if (pos > 1) {      System.arraycopy(buffer, 1, buffer, 0, pos - 1);    }    pos--;    return b;  }}


    最新回复(0)