从InputStream读取行而不进行缓冲 [英] Reading lines from an InputStream without buffering

查看:86
本文介绍了从InputStream读取行而不进行缓冲的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java有一个简单的方法来从InputStream中读取一行而不进行缓冲吗? BufferedReader不适合我的需要,因为我需要重复通过相同的连接传输文本和二进制数据,缓冲只会妨碍。

Does Java have a simple method to read a line from an InputStream without buffering? BufferedReader is not suitable for my needs because I need to transfer both text and binary data through the same connection repeatedly and buffering just gets in the way.

推荐答案

最终手动直接从InputStream读取字节,而不包装InputStream。我尝试过的所有内容,如Scanner和InputStreamReader,都会向前读取(缓冲区)输入:(

Eventually did it manually directly reading byte after byte from the InputStream without wrapping the InputStream. Everything I tried, like Scanner and InputStreamReader, reads ahead (buffers) the input :(

我想我错过了一些像\r。

I guess I missed a some cases like \r.

public static String readLine(InputStream inputStream) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    int c;
    for (c = inputStream.read(); c != '\n' && c != -1 ; c = inputStream.read()) {
        byteArrayOutputStream.write(c);
    }
    if (c == -1 && byteArrayOutputStream.size() == 0) {
        return null;
    }
    String line = byteArrayOutputStream.toString("UTF-8");
    return line;
}

这篇关于从InputStream读取行而不进行缓冲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆