📜  Java中的 Deflater setInput()函数及示例

📅  最后修改于: 2022-05-13 01:55:41.470000             🧑  作者: Mango

Java中的 Deflater setInput()函数及示例


Java .util.zipDeflater 类setInput()函数用于设置输入数据进行压缩。当needsInput()返回 true 表示输入缓冲区为空时,应调用此函数。

函数签名:

public void setInput(byte[] b)
public void setInput(byte[] b, int offset, int len)

句法:

d.setInput(byte[]);
d.setInput(byte[], int, int);

参数:这些重载函数接受的各种参数有:

  • byte[] b :这是要压缩的输入数组
  • int offset :这是在给定数组中读取值的起始偏移量
  • int length :这是从起始偏移量压缩的最大长度。

返回类型:函数没有返回任何东西。

异常:函数没有抛出任何异常

示例 1:

// Java program to describe the use
// of setInput(byte[] b) function
  
import java.util.zip.*;
import java.io.UnsupportedEncodingException;
  
class GFG {
    public static void main(String args[])
        throws UnsupportedEncodingException
    {
        // deflater
        Deflater d = new Deflater();
  
        // get the text
        String pattern = "GeeksforGeeks", text = "";
  
        // generate the text
        for (int i = 0; i < 4; i++)
            text += pattern;
  
        // 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 :"
                           + new String(output)
                           + "\n Size " + size);
  
        // original String
        System.out.println("Original String :" + text
                           + "\n Size " + text.length());
  
        // end
        d.end();
    }
}

输出:

Compressed String :x?sOM?.N?/r???q??
 Size 21
Original String :GeeksforGeeksGeeksforGeeksGeeksforGeeksGeeksforGeeks
 Size 52

示例 2:

// Java program to describe the use
// of setInput(byte[] b, int offset, int len) function
  
import java.util.zip.*;
import java.io.UnsupportedEncodingException;
  
class GFG {
    public static void main(String args[])
        throws UnsupportedEncodingException
    {
        // deflater
        Deflater d = new Deflater();
  
        // get the text
        String pattern = "GeeksforGeeks", text = "";
  
        // generate the text
        for (int i = 0; i < 4; i++)
            text += pattern;
  
        // set the Input for deflator
        d.setInput(text.getBytes("UTF-8"), 10, 30);
  
        // 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 :"
                           + new String(output)
                           + "\n Size " + size);
  
        // end
        d.end();
    }
}

输出:

Compressed String :x?K?.vOM?.N?/????
 Size 22

参考: https: Java/util/zip/Deflater.html#setInput()