Java中使用Deflate和Inflate类的Zlib压缩

Java中使用Deflate和Inflate类的Zlib压缩,java,compression,zlib,deflate,inflate,Java,Compression,Zlib,Deflate,Inflate,我想尝试使用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.I

我想尝试使用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");

    }
}

你想在这里干什么?您使用一个充气器输入流来解压缩您的数据,然后尝试再次将此解压缩数据传递给充气器?使用其中一个,但不能同时使用两个

这就是导致您出现异常的原因

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

  • 在循环中完成压缩-完成后,无法添加更多数据
  • 您不会检查放气过程产生的输出量。如果您有长行,则可能超过1024字节
  • 您设置了充气机的输入,但也没有设置长度
    a
我还发现了一些:

  • 写入后(以及从同一文件读取前)不会关闭FileOutputStream
  • 您可以使用
    readLine()
    读取一行文本,但不需要再次添加换行符,这意味着解压文件中不会出现任何换行符
  • 您无需将字节转换为字符串,然后再转换为字节
  • 您创建了以后不使用的变量
我不会试图纠正你的程序。这里有一个简单的,我认为你想要的,使用DeflaterOutputStream和InflaterInputStream。(您也可以使用JZlib的ZInputStream和ZOutputStream代替。)

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

的代码可以通过使用以下方法进一步改进:


那是家庭作业吗?一个错误是调用finish太早,另一个错误是使用setInput w/o length,还有一个错误是没有检查deflate进程返回的数据是否超过1024。您确定这是针对zlib的吗。我试图解压缩zlib文件,但得到了一个
未知的压缩方法
错误。如果我看一下,我会看到
充气机
提到zlib,但您使用的
充气机输入流
提到了放气压缩方法。这是文件:InflaterInputStream使用一个
新充气器()
(如果使用不带充气器参数的构造函数)。这个构造函数使用
nowrap=false
,这意味着zlib压缩。(我没有检查你的文件。)扫描仪的目标是什么?刚刚获取流的第一行?@Paŭlo Ebermann:这是一个一次性读取整个流的技巧。为什么
缓冲(输入输出)putStream
不存在?Stephan:没有特别的原因,代码工作正常。也许更大的文件包含缓冲版本会更快
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"));
    }
}
import java.util.Scanner;
import java.util.zip.*;
import java.io.*;

public class ZLibCompression
{
    public static void compress(File raw, File compressed) throws IOException
    {
        try (InputStream inputStream = new FileInputStream(raw);
             OutputStream outputStream = new DeflaterOutputStream(new FileOutputStream(compressed)))
        {
            copy(inputStream, outputStream);
        }
    }

    public static void decompress(File compressed, File raw)
            throws IOException
    {
        try (InputStream inputStream = new InflaterInputStream(new FileInputStream(compressed));
             OutputStream outputStream = new FileOutputStream(raw))
        {
            copy(inputStream, outputStream);
        }
    }

    public static String decompress(File compressed) throws IOException
    {
        try (InputStream inputStream = new InflaterInputStream(new FileInputStream(compressed)))
        {
            return toString(inputStream);
        }
    }

    private static String toString(InputStream inputStream)
    {
        try (Scanner scanner = new Scanner(inputStream).useDelimiter("\\A"))
        {
            return scanner.hasNext() ? scanner.next() : "";
        }
    }

    private static void copy(InputStream inputStream, OutputStream outputStream)
            throws IOException
    {
        byte[] buffer = new byte[1000];
        int length;

        while ((length = inputStream.read(buffer)) > 0)
        {
            outputStream.write(buffer, 0, length);
        }
    }
}