Java 使用gzip格式的缓冲区解压缩图像失败

Java 使用gzip格式的缓冲区解压缩图像失败,java,gzip,Java,Gzip,我正在使用压缩文件,但在解压缩文件时,我面临两个问题 当在没有缓冲区的情况下解压时,它将返回到原始形式,但当我使用缓冲区时,它无法正确地执行 解压缩文件的大小大于原始文件的大小 您不是在写缓冲区,而是在写数据,它是读取的字节长度 更正: private static void writeFile(FileOutputStream fos, String zipFilePath) throws IOException { byte[] buffer = new byte[12048];

我正在使用压缩文件,但在解压缩文件时,我面临两个问题

  • 在没有缓冲区的情况下解压时,它将返回到原始形式,但当我使用缓冲区时,它无法正确地执行

  • 解压缩文件的大小大于原始文件的大小


  • 您不是在写
    缓冲区
    ,而是在写
    数据
    ,它是读取的字节长度

    更正:

    private static void writeFile(FileOutputStream fos, String zipFilePath) throws IOException {
        byte[] buffer = new byte[12048];
        try (InputStream fis = new FileInputStream(zipFilePath);
             InputStream inflaterInputStream = new GZIPInputStream(fis)) {
             int data;
             while ((data = inflaterInputStream.read(buffer)) != -1) {//with buffer**
                 fos.write(buffer, 0, data);
             }
        }
    }
    
    您最好使用apache.commons io

    private static void writeFile(FileOutputStream fos, String zipFilePath) throws IOException {
        try (InputStream fis = new FileInputStream(zipFilePath);
             InputStream inflaterInputStream = new GZIPInputStream(fis)) {
            IOUtils.copy(fis, fos);
        }
    }
    
    private static void writeFile(FileOutputStream fos, String zipFilePath) throws IOException {
        try (InputStream fis = new FileInputStream(zipFilePath);
             InputStream inflaterInputStream = new GZIPInputStream(fis)) {
            IOUtils.copy(fis, fos);
        }
    }