如何对 Java 上的文件进行 GZIP 压缩并通过 OutputStream 发送

How to GZIP files on Java and send it through the OutputStream

我正在使用 GZIPOutputStream class 对图像进行 GZIP 压缩。当我尝试通过 OutputStream 发送 GZIP 文件时,我收到了损坏的文件。我知道如何 GZIP 到 FileOutputStream。以下代码完美运行:

Static private void GZIPCompress(String fileName)
{
        File file = new File(fileName);
        FileInputStream fis = new FileInputStream(file);
        byte[] data = new byte[(int) file.length()];

        fis.read(data); 
        FileOutputStream fos = new FileOutputStream(fileName + ".gz");
        GZIPOutputStream gzos = new GZIPOutputStream(fos); 
        gzos.write(data);
        fos.close();
        fis.close();
 }

输出文件是 myfile.png.gz 并且具有以下 详细信息

myfile.png.gz: gzip compressed data, from FAT filesystem (MS-DOS, OS/2, NT)

我的问题是当我尝试对文件进行 GZIP 压缩并将其发送到 OutputStream 时。因为我正在使用服务器,所以我从我的服务器调用它并且我正在使用套接字。

Static void SendGZIPFile(String fileName, OutputStream os)
{
        DataOutputStream dos = new DataOutputStream(os);
        File file = new File(fileName);
        FileInputStream fis = new FileInputStream(file);
        byte[] data = new byte[(int) file.length()];
        byte[] dataAux = new byte[(int) file.length()];
        dos.writeBytes("HTTP/1.1 200 OK\r\n");
        dos.writeBytes("Content-Type: application/x-gzip \r\n");
        dos.writeBytes("Content-Disposition: form-data; filename="+"\""+fileName+".gz"+"\""+"\n");
        dos.writeBytes("\r\n\r\n");
        dos = new DataOutputStream(new GZIPOutputStream(os));
        fis.read(data);
        dos.write(data);
        dos.close();
        fis.close();
        gzos.close();
}

我得到的是一个损坏的 GZIP 文件,其中不包含任何内容:这里是 详细信息

myfile.gz data

我认为我在 GZip 压缩时做错了什么,因为我注意到 细节 之间的差异。我使用以下命令来获取它:file myfile.gz

关闭 dos 前刷新 gzos。或者先关闭gzos

除了你的代码缺乏基本的正确性(你可能不应该在你的代码中实现 HTTP,过去聪明的人已经这样做了),我认为问题是你没有正确复制数据。相反,您应该像这样循环复制:

byte[] buf = new byte[1024];
int len;
while((len = fis.read(buf)) != -1)
{
    dos.write(buf, 0, len);
}

或者您可以只使用 Apache Commons IO:

IOUtils.copy(fis, dos);