当前位置: 首页 > 面试题库 >

在Java中使用Deflate和Inflate类进行Zlib压缩

解晟睿
2023-03-14
问题内容

我想尝试将java.util.zip中的Deflate和Inflate类用于zlib压缩。

我可以使用Deflate压缩代码,但是在解压缩时却遇到此错误-

Exception in thread "main" java.util.zip.DataFormatException: unknown compression method
    at java.util.zip.Inflater.inflateBytes(Native Method)
    at java.util.zip.Inflater.inflate(Inflater.java:238)
    at java.util.zip.Inflater.inflate(Inflater.java:256)
    at zlibCompression.main(zlibCompression.java:53)

到目前为止,这是我的代码-

import java.util.zip.*;
import java.io.*;

public class zlibCompression {

    /**
     * @param args
     */
    public static void main(String[] args) throws IOException, DataFormatException {
        // TODO Auto-generated method stub

        String fname = "book1";
        FileReader infile = new FileReader(fname);
        BufferedReader in = new BufferedReader(infile);

        FileOutputStream out = new FileOutputStream("book1out.dfl");
        //BufferedInputStream in = new BufferedInputStream(new FileInputStream(filename));

        Deflater compress = new Deflater();
        Inflater decompress = new Inflater();

        String readFile = in.readLine();
        byte[] bx = readFile.getBytes();

        while(readFile!=null){
            byte[] input = readFile.getBytes();
            byte[] compressedData = new byte[1024];
            compress.setInput(input);
            compress.finish();
            int compressLength = compress.deflate(compressedData, 0, compressedData.length);
            //System.out.println(compressedData);
            out.write(compressedData, 0, compressLength);
            readFile = in.readLine();
        }

        File abc = new File("book1out.dfl");
        InputStream is = new FileInputStream("book1out.dfl");

        InflaterInputStream infl = new InflaterInputStream(new FileInputStream("book1out.dfl"), new Inflater());
        FileOutputStream outFile = new FileOutputStream("decompressed.txt");

        byte[] b = new byte[1024];
        while(true){

            int a = infl.read(b,0,1024);
            if(a==0)
                break;

            decompress.setInput(b);
            byte[] fresult = new byte[1024];
            //decompress.in
            int resLength = decompress.inflate(fresult);
            //outFile.write(b,0,1);
            //String outt = new String(fresult, 0, resLength);
            //System.out.println(outt);
        }

        System.out.println("complete");

    }
}

问题答案:

您想在这里做什么?您使用InflaterInputStream来解压缩数据,然后尝试再次将此解压缩后的数据传递给Inflater?使用其中之一,但不能同时使用。

这就是导致您的异常的原因。

除此之外,还有一些小错误,例如bestsss提到的错误:

  • 您在循环中完成了压缩-完成后,无法再添加任何数据。
  • 您无需检查放气过程会产生多少输出。如果行很长,则可能超过1024个字节。
  • 您也可以在不设置长度的情况下将输入设置为充气机a

我发现了更多:

  • 写入后(和从同一文件读取之前),不要关闭FileOutputStream。
  • readLine()曾经使用过读取一行文本,但随后不再添加换行符,这意味着在解压缩的文件中将不会出现任何换行符。
  • 您可以从字节转换为字符串,然后再转换为字节,而无需任何操作。
  • 您将创建稍后不使用的变量。

我不会尝试更正您的程序。这是一个简单的示例,它使用DeflaterOutputStream和InflaterInputStream来满足您的要求。(您也可以改用JZlib的ZInputStream和ZOutputStream。)

import java.util.zip.*;
import java.io.*;

/**
 * Example program to demonstrate how to use zlib compression with
 * Java.
 * Inspired by http://stackoverflow.com/q/6173920/600500.
 */
public class ZlibCompression {

    /**
     * Compresses a file with zlib compression.
     */
    public static void compressFile(File raw, File compressed)
        throws IOException
    {
        InputStream in = new FileInputStream(raw);
        OutputStream out =
            new DeflaterOutputStream(new FileOutputStream(compressed));
        shovelInToOut(in, out);
        in.close();
        out.close();
    }

    /**
     * Decompresses a zlib compressed file.
     */
    public static void decompressFile(File compressed, File raw)
        throws IOException
    {
        InputStream in =
            new InflaterInputStream(new FileInputStream(compressed));
        OutputStream out = new FileOutputStream(raw);
        shovelInToOut(in, out);
        in.close();
        out.close();
    }

    /**
     * Shovels all data from an input stream to an output stream.
     */
    private static void shovelInToOut(InputStream in, OutputStream out)
        throws IOException
    {
        byte[] buffer = new byte[1000];
        int len;
        while((len = in.read(buffer)) > 0) {
            out.write(buffer, 0, len);
        }
    }


    /**
     * Main method to test it all.
     */
    public static void main(String[] args) throws IOException, DataFormatException {
        File compressed = new File("book1out.dfl");
        compressFile(new File("book1"), compressed);
        decompressFile(compressed, new File("decompressed.txt"));
    }
}

为了提高效率,用缓冲流包装文件流可能很有用。如果这对性能至关重要,请对其进行测量。



 类似资料:
  • 问题内容: 有人可以向我解释zlib库在Nodejs中如何工作吗? 我对Node.js很陌生,还不确定如何使用缓冲区和流。 我的简单情况是一个字符串变量,我想将字符串压缩或解压缩(压缩或膨胀,gzip或gunzip等)到另一个字符串。 即(我希望它如何工作) 感谢您的帮助:) 问题答案: 更新 :没意识到在节点0.5中有一个新的内置“ zlib”模块。我在下面的答案是针对第三方node- zlib

  • 处理内存中的数据 # zlib_memory.py import zlib import binascii original_data = b'This is the original text.' print('Original :', len(original_data), original_data) compressed = zlib.compress(original_dat

  • Stability: 2 - Stable zlib 模块提供通过 Gzip 和 Deflate/Inflate 实现的压缩功能,可以通过这样使用它 const zlib = require('zlib'); 压缩或者解压数据流(例如一个文件)通过zlib流将源数据流传输到目标流中来完成。 const gzip = zlib.createGzip(); const fs = require('f

  • 问题内容: 我试图弄清楚如何轻松发送HTTP / HTTPS请求以及处理gzip / deflate压缩响应以及cookie的最佳方法。 我发现最好的是https://github.com/mikeal/request,它可以处理 除 压缩 以外的 所有内容。是否有模块或方法可以满足我的要求? 如果没有,我可以某种方式组合请求和zlib吗?我尝试将zlib和组合在一起,但失败了。 问题答案: 注意

  • 问题内容: 我在将png转换为tiff时遇到问题。转换很好,但是图像很大。我认为问题是我没有正确执行压缩?有人有什么建议吗? 这是代码示例 问题答案: 仅创建一个对象,不会将其链接回其他任何对象。 我看不到您的代码中有任何机制可用于。 我相信代替: 您需要使用:

  • 我的javascript代码是 它运行时显示消息错误“不支持的压缩方法”。但是我尝试用在线工具http://i-tools.org/gzip解压,它返回正确的字符串。