从InputStream读取行而不进行缓冲 [英] Reading lines from an InputStream without buffering
问题描述
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屋!