如何在不缓冲输入的情况下从InputStream中读取一行? [英] How to read a line from InputStream without buffering the input?

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

问题描述

我有一个InputStream,它包含一个字符串作为字符串,然后是二进制数据。



如果我使用读取新行BufferedReader(new InputStreamReader(inputStream)),二进制数据也被读取,无法重新读取。



如何在不读取的情况下读取一行二进制数据呢?

解决方案

最终手动直接从InputStream读取字节,而不包装InputStream。一切我想,像扫描仪和InputStreamReader的,预读(缓冲区)输入:(



我想我错过了一些情况下,像\r



'pre> 公共静态字符串的readLine(InputStream的的inputStream)抛出IOException异常{
byteArrayOutputStream byteArrayOutputStream =新byteArrayOutputStream();
诠释三;
。对于(C = inputStream.read();!C = '\\\
' &安培;&安培;!C = -1; C = inputStream.read()){
byteArrayOutputStream.write(c)中;
}
if(c == -1&& byteArrayOutputStream.size()== 0){
return null;
}
String line = byteArrayOutputStream.toString(UTF-8);
返回行;
}


I have an InputStream which contains a line as a string and then binary data.

If I read the line using new BufferedReader(new InputStreamReader(inputStream)), the binary data is being also read and cannot be re-read.

How can I read a line without reading the binary data as well?

解决方案

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 :(

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天全站免登陆