Beispiel #1
1
  // tokenizes a string for PBM and PGM headers and plain PBM and PGM data.  If oneChar is true,
  // then
  // rather than parsing a whole string, a single character is read (not including whitespace or
  // comments)
  static String tokenizeString(InputStream stream, boolean oneChar) throws IOException {
    final int EOF = -1;

    StringBuilder b = new StringBuilder();
    int c;
    boolean inComment = false;

    while (true) {
      c = stream.read();
      if (c == EOF)
        throw new IOException(
            "Stream ended prematurely, before table reading was completed."); // no more tokens
      else if (inComment) {
        if (c == '\r' || c == '\n') // escape the comment
        inComment = false;
        else {
        } // do nothing
      } else if (Character.isWhitespace((char) c)) {
      } // do nothing
      else if (c == '#') // start of a comment
      {
        inComment = true;
      } else // start of a string
      {
        b.append((char) c);
        break;
      }
    }

    if (oneChar) return b.toString();

    // at this point we have a valid string.  We read until whitespace or a #
    while (true) {
      c = stream.read();
      if (c == EOF) break;
      else if (c == '#') // start of comment, read until a '\n'
      {
        while (true) {
          c = stream.read(); // could hit EOF, which is fine
          if (c == EOF) break;
          else if (c == '\r' || c == '\n') break;
        }
        // break;   // comments are not delimiters
      } else if (Character.isWhitespace((char) c)) break;
      else b.append((char) c);
    }
    return b.toString();
  }