BufferedReader for large ByteBuffer?

后端 未结 3 1250
悲哀的现实
悲哀的现实 2021-01-20 05:37

Is there a way to read a ByteBuffer with a BufferedReader without having to turn it into a String first? I want to read through a fairly large ByteBuffer as lines of text an

3条回答
  •  抹茶落季
    2021-01-20 05:57

    This is a sample:

    public class ByteBufferBackedInputStream extends InputStream {
    
        ByteBuffer buf;
    
        public ByteBufferBackedInputStream(ByteBuffer buf) {
            this.buf = buf;
        }
    
        public synchronized int read() throws IOException {
            if (!buf.hasRemaining()) {
                return -1;
            }
            return buf.get() & 0xFF;
        }
    
        @Override
        public int available() throws IOException {
            return buf.remaining();
        }
    
        public synchronized int read(byte[] bytes, int off, int len) throws IOException {
            if (!buf.hasRemaining()) {
                return -1;
            }
    
            len = Math.min(len, buf.remaining());
            buf.get(bytes, off, len);
            return len;
        }
    }
    

    And you can use it like this:

        String text = "this is text";   // It can be Unicode text
        ByteBuffer buffer = ByteBuffer.wrap(text.getBytes("UTF-8"));
    
        InputStream is = new ByteBufferBackedInputStream(buffer);
        InputStreamReader r = new InputStreamReader(is, "UTF-8");
        BufferedReader br = new BufferedReader(r);
    

提交回复
热议问题