Reading lines from an InputStream without buffering

别说谁变了你拦得住时间么 提交于 2020-01-20 06:43:07

问题


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.


回答1:


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;
}



回答2:


You could try the Scanner class: http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

However, this may buffer the input if no newline characters are present:

Since this method continues to search through the input looking for a line separator, it may buffer all of the input searching for the line to skip if no line separators are present.




回答3:


You may be better off reading the InputStream with a BufferedReader and appending the read lines to a String.

You can then manipulate the String as you wish without worrying about buffering.



来源:https://stackoverflow.com/questions/8488433/reading-lines-from-an-inputstream-without-buffering

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!