How to read a line from InputStream without buffering the input? [duplicate]

痴心易碎 提交于 2019-12-05 15:33:16

* Update: It seems that InputStreamReader buffers (reads ahead) as well :( Posted another answer to directly read from the InputStream.

Eventually did it manually :(

I guess I missed a lot of cases like \r and white spaces.

public static String readLine(InputStream inputStream) throws IOException {
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
    StringBuilder stringBuilder = new StringBuilder();
    int c;
    for (c = reader.read(); c != '\n' && c != -1 ; c = reader.read()) {
        stringBuilder.append((char)c);
    }
    if (c == -1 && stringBuilder.length() == 0) return null; // End of stream and nothing to return
    return stringBuilder.toString();
}

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

Have you tried DataInputStream ?

You Could try Scanner Class.... (java.util.Scanner;)

Scanner in = new Scanner(System.in);

String Str = in.nextLine();

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