Java Deflater setLevel()函数及示例
java.util.zip中 Deflater类 的 setLevel() 函数将当前的压缩级别设置为指定值。压缩级别是一个从0到9的整数值。
函数签名
public void setLevel(int level)
语法
d.setLevel(int);
参数: 该函数需要一个整数值,该值是指定的压缩值。
返回类型: 该函数不返回任何值。
异常: 如果压缩级别无效,该函数会抛出IllegalArgumentException。
一些deflater级别的常量值。
- BEST_COMPRESSION : 最佳压缩的压缩级别
 - BEST_SPEED : 最快压缩的压缩级别。
 - DEFAULT_COMPRESSION : 默认压缩级别。
 - NO_COMPRESSION : 不压缩的压缩级别。
 
例子 1 :
// Java program to describe the use
// of setLevel() function
  
import java.util.zip.*;
import java.io.UnsupportedEncodingException;
  
class GFG {
  
    // Function to compress the string to the given level
    static void compression(int level, String text)
        throws UnsupportedEncodingException
    {
        // deflater
        Deflater d = new Deflater(level);
  
        // set the Input for deflator
        d.setInput(text.getBytes("UTF-8"));
  
        // finish
        d.finish();
  
        // output bytes
        byte output[] = new byte[1024];
  
        // compress the data
        int size = d.deflate(output);
  
        // compressed String
        System.out.println("Compressed String with level ="
                           + level + " :"
                           + new String(output)
                           + "\n Size " + size);
  
        d.end();
    }
  
    // Driver code
    public static void main(String args[])
        throws UnsupportedEncodingException
    {
  
        // get the text
        String pattern = "GeeksforGeeks", text = "";
  
        // generate the text
        for (int i = 0; i < 4; i++)
            text += pattern;
  
        // original String
        System.out.println("Original String :" + text
                           + "\n Size " + text.length());
  
        // default
        compression(Deflater.DEFAULT_COMPRESSION, text);
  
        // no compression
        compression(Deflater.NO_COMPRESSION, text);
  
        // Best compression
        compression(Deflater.BEST_COMPRESSION, text);
  
        // Best Speed
        compression(Deflater.BEST_SPEED, text);
    }
}
输出
Original String :GeeksforGeeksGeeksforGeeksGeeksforGeeksGeeksforGeeks
 Size 52
Compressed String with level =-1 :x?sOM?.N?/r???q??
 Size 21
Compressed String with level =0 :x4??GeeksforGeeksGeeksforGeeksGeeksforGeeksGeeksforGeeks??
 Size 63
Compressed String with level =9 :x?sOM?.N?/r???q??
 Size 21
Compressed String with level =1 :xsOM?.N?/r?`?0??
 Size 22

参考资料: https://docs.oracle.com/javase/7/docs/api/java/util/zip/Deflater.html#setLevel()
极客教程