如何使用BufferedInputStream包装GZipInputStream?

时间:2017-06-19 17:40:02

标签: java buffer inputstream bufferedinputstream gzipinputstream

我有一个FileReadClient,它按如下方式读取文件,

     public synchronized int read (byte buf[], int off, int len) throws IOException {
        if (br == null){
          if (useGZIP) {
            br = new BufferedInputStream(new GZIPInputStream(blockStream));
          } else {
           br = new BufferedInputStream(blockStream);
          }
        }
    int result = br.read(buf, off, len);
    return result;
    }

这是我的FileDownloadServlet,它会读取文件内容并将其写入ServletOutputStream

  InputStream fileStream; //This is an instance of `FileReadClient`
  int c = 0;
  int BUF_LEN = 4096;
  byte bufr[] = new byte[BUF_LEN];
  while ((c = fileStream.read(bufr, 0, BUF_LEN)) != -1) {
    servletOutStream.write(bufr, 0, c);
  }

我将我的文件存储为压缩文件,因此在阅读原始文件时,我的文件使用GZIPInputStream中的FileReadClient解压缩

案例1:

我所能看到的是read()FileReadClient的调用完全读取8192个字节,而FileDownloadServlet读取4096个字节两次。虽然我在read()调用时将缓冲区长度设置为8192,但我无法理解它最初是如何读取4096个字节的。

案例2:

现在我正在从FileReadClient以压缩格式读取文件并将其传递给我的输入流

public class MyInputStream extends java.io.InputStream {

String filepath = "";
boolean decompressByFileReadClient = true;
InputStream in;
public MyInputStream(Sting filepath, boolean decompressByFileReadClient) {
  this.filepath = filepath;
  initInputStream();
}
public void initInputStream() {
  this.in = new FileReadClient();   //This reads data as compressed from file read client
  if(!decompressByFileReadClient) {
     this.in = new GZIPInputStream(this.in); //Pass "FileReadClient" input stream to GZIPInputStream to decompress the file content here 
     //This reads only 512 bytes at a time - since the default buffer size for GZIPInputStream is 512 bytes
  }
 }
}

现在,当我从FileDownloadServletMyInputStream读取我的文件内容时,我只能读取512字节的数据 - 尽管我用BufferInputStream打包 - 这使得{{1}这里毫无意义。

现在,虽然读取期间缓冲区大小为4K,但由于BufferInputStreamMyInputStream一次只读取512个字节。因此,读取调用的数量会增加,这会增加文件下载延迟。

从InputStream读取期间的系统调用次数我们可以使用BufferedInputStream(它读取输入流中可用的字节数,直到缓冲区可以容纳 - reference)。同样,当我使用GZIPInputStream时,如何与BufferedInputStream类似地减少阅读次数?

欢迎任何建议!在此先感谢: - )

0 个答案:

没有答案