简体   繁体   English

如何解压缩文件并将其读取到Java中的ByteBuffer?

[英]How do I uncompress a file and read it to the ByteBuffer in java?

I have a piece of code like so... 我有一段这样的代码...

FileInputStream fi = new FileInputStream(filein);
GZIPInputStream gzis = new GZIPInputStream(fi);
ByteBuffer bbuffer = ByteBuffer.allocate(115200);

The fi.available() is 84300, but the gzis.available() is only 1. The file(filein) is already compressed. fi.available()为84300,但gzis.available()仅为file(filein)已被压缩。

I want to read the file, uncompress it, and finally put it into my ByteBuffer bbufer . 我想读取文件,将其解压缩,最后将其放入ByteBuffer bbufer

How could I realize this operation? 我怎么能实现这一操作?

gzis.available() = 1; doesn't mean that there is a problem, it simply means that you can only read 1 byte of information from the Stream before you can continue. 这并不意味着存在问题,而只是意味着您只能从Stream中读取1个字节的信息,然后才能继续。 you can't expect that the entire uncompressed file will be available in a single command. 您不能期望整个未压缩的文件将在单个命令中可用。

To read the entire file, you will need to have a loop that continues to read over the InputStream until you have all the data. 要读取整个文件,您将需要有一个循环,该循环将继续读取InputStream,直到获得所有数据为止。 For example... 例如...

int bytesRead = 0;
int bytesAvailable = gzis.available();
while (bytesAvailable > 0){
    gzis.read(bbuffer,bytesRead,bytesAvailable);
    bytesRead += bytesAvailable;
    bytesAvailable = gzis.available();
}

Of course, if you aren't sure of the final size of the uncompressed file, you'll need to add in extra code to allow your bbuffer to be resized if you need more room. 当然,如果不确定未压缩文件的最终大小,则需要添加额外的代码,以便在需要更多空间时调整bbuffer大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM