Reading Strings and Binary from the same FileInputStream

前端 未结 7 1980
离开以前
离开以前 2021-01-17 22:29

I have a file that contains some amount of plain text at the start followed by binary content at the end. The size of the binary content is determined by some one of the pla

7条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 22:41

    Alas, DataInputStream is deprecated and does not handle UTF. But this should help (it reads a line from a binary stream, without any lookahead).

    public static String lineFrom(InputStream in) throws IOException {
        byte[] buf = new byte[128];
        int pos = 0;
        for (;;) {
            int ch = in.read();
            if (ch == '\n' || ch < 0) break;
            buf[pos++] = (byte) ch;
            if (pos == buf.length) buf = Arrays.copyOf(buf, pos + 128);
        }
        return new String(Arrays.copyOf(buf, pos), "UTF-8");
    }
    

提交回复
热议问题