Reading lines from an InputStream without buffering

后端 未结 3 1692
独厮守ぢ
独厮守ぢ 2020-12-19 12:51

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 bin

3条回答
  •  情话喂你
    2020-12-19 13:19

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

提交回复
热议问题