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

北战南征 提交于 2019-12-10 09:21:20

问题


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?


回答1:


* 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();
}



回答2:


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



回答3:


Have you tried DataInputStream ?




回答4:


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

Scanner in = new Scanner(System.in);

String Str = in.nextLine();



来源:https://stackoverflow.com/questions/25215564/how-to-read-a-line-from-inputstream-without-buffering-the-input

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