Reads the token starting at the current stream position and ending at the first occurrence of the given delimiter byte, in the given encoding. If LF is specified as the delimiter, a CRLF pair is also treated as one. @param in the stream from which the token is read @param delim the byte value which
(InputStream in, int delim,
String enc, int maxLength)
| 2737 | * is reached before the token end is reached |
| 2738 | */ |
| 2739 | public static String readToken(InputStream in, int delim, |
| 2740 | String enc, int maxLength) throws IOException { |
| 2741 | // note: we avoid using a ByteArrayOutputStream here because it |
| 2742 | // suffers the overhead of synchronization for each byte written |
| 2743 | int b; |
| 2744 | int len = 0; // buffer length |
| 2745 | int count = 0; // number of read bytes |
| 2746 | byte[] buf = null; // optimization - lazy allocation only if necessary |
| 2747 | while ((b = in.read()) != -1 && b != delim) { |
| 2748 | if (count == len) { // expand buffer |
| 2749 | if (count == maxLength) |
| 2750 | throw new IOException("token too large (" + count + ")"); |
| 2751 | len = len > 0 ? 2 * len : 256; // start small, double each expansion |
| 2752 | len = maxLength < len ? maxLength : len; |
| 2753 | byte[] expanded = new byte[len]; |
| 2754 | if (buf != null) |
| 2755 | System.arraycopy(buf, 0, expanded, 0, count); |
| 2756 | buf = expanded; |
| 2757 | } |
| 2758 | buf[count++] = (byte)b; |
| 2759 | } |
| 2760 | if (b < 0 && delim != -1) |
| 2761 | throw new EOFException("unexpected end of stream"); |
| 2762 | if (delim == '\n' && count > 0 && buf[count - 1] == '\r') |
| 2763 | count--; |
| 2764 | return count > 0 ? new String(buf, 0, count, enc) : ""; |
| 2765 | } |
| 2766 | |
| 2767 | /** |
| 2768 | * Reads the ISO-8859-1 encoded string starting at the current stream |
no test coverage detected