InputStream---readLine(可自己指定编码)

         声明:文章内容全都是自己的学习总结,如有不对的地方请大家帮忙指出。有需要沟通交流的可加我QQ群:425120333
         BufferedReader 有个readLine(),能够将文件按行读取,不过这里的读取编码是不能指定的,只有将InputStream装饰成BufferedReader才能
    使用readLine()方法,好奇之下就是看了readLine方法的源码,参考这个源码做了一些改动,目的是为了使得InputStream不必装饰成BufferedReader,
    也可以做到一行行读取,并且能指定编码(虽然有点多余,不过主要是学习下实现功能的过程。)
/**@introduce 按行读取输入流
 * @param in
 * @param charset
 * @return
 * @throws IOException
 */
public static String readLine(InputStream in,String charset) throws IOException {
    byte[] lineBuffer = new byte[128];
    byte[] buf = lineBuffer;

    int room = buf.length;
    int offset = 0;
    int c;

    loop: while (true) {
        switch (c = in.read()) {
            case -1:
            case '\n':
                break loop;

            case '\r':
                int c2 = in.read();
                if ((c2 != '\n') && (c2 != -1)) {
                    if (!(in instanceof PushbackInputStream)) {
                        in = new PushbackInputStream(in);
                    }
                    ((PushbackInputStream) in).unread(c2);
                }
                break loop;

            default:
                if (--room < 0) {
                    buf = new byte[offset + 128];
                    room = buf.length - offset - 1;
                    System.arraycopy(lineBuffer, 0, buf, 0, offset);
                    lineBuffer = buf;
                }
                buf[offset++] = (byte) c;
                break;
        }
    }
    if ((c == -1) && (offset == 0)) {
        return null;
    }
    lineBuffer = new byte[offset];
    System.arraycopy(buf, 0, lineBuffer, 0, offset);
    return new String(lineBuffer, charset);
}
通过这个工具方法就可以将InputStream接口下的所有类都能按行读取,而且能够指定编码格式(附加的)。

你可能感兴趣的:(Java随笔---实用工具类)