Android: read a GZIP file in the ASSETS folder

后端 未结 6 1360
不思量自难忘°
不思量自难忘° 2021-01-06 08:07

How can you read GZIP file in Android located in the \"ASSETS\" (or resources/raw) folder?

I have tried the following code, but my stream size is always 1.



        
6条回答
  •  星月不相逢
    2021-01-06 08:27

    this is the documented behavior of InflaterInputStream.available:

    http://java.sun.com/javase/6/docs/api/java/util/zip/InflaterInputStream.html#available()

    Returns 0 after EOF has been reached, otherwise always return 1.
    

    abusing available is a common mistake --- in no case can you assume that it tells you the length of a file (though it sometimes happens to do so, as you've noticed). you want to keep calling read(byte[], int, int) until it returns 0. if you want the length to allocate a byte[] up front, you probably want to create a ByteArrayOutputStream and write to that each time you read, and then get a byte[] from that when you exit the loop. this works for all InputStreams in all cases.

提交回复
热议问题