Java InputStream reading problem

前端 未结 4 1917

I have a Java class, where I\'m reading data in via an InputStream

    byte[] b = null;
    try {
        b = new byte[in.available()];
        in.read(b);
          


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-16 20:15

    read() will return -1 when the InputStream is depleted. There is also a version of read which takes an array, this allows you to do chunked reads. It returns the number of bytes actually read or -1 when at the end of the InputStream. Combine this with a dynamic buffer such as ByteArrayOutputStream to get the following:

    InputStream in = ...
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int read;
    byte[] input = new byte[4096];
    while ( -1 != ( read = in.read( input ) ) ) {
        buffer.write( input, 0, read );
    }
    input = buffer.toByteArray()
    

    This cuts down a lot on the number of methods you have to invoke and allows the ByteArrayOutputStream to grow its internal buffer faster.

提交回复
热议问题