HOWTO · Java

在 Java 中压缩字符串

本教程演示了如何使用 deflater 在 Java 中压缩字符串。

当我们想要节省内存时,需要压缩字符串。在 Java 中,deflater 用于以字节为单位压缩字符串。

本教程将演示如何在 Java 中压缩字符串。

在 Java 中使用 deflater 压缩字符串

deflater 是 Java 中的对象创建器,它压缩输入数据并用压缩数据填充指定的缓冲区。

例子:

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

class Compress_Class {
  public static void main(String args[]) throws UnsupportedEncodingException {
    // Using the deflater object
    Deflater new_deflater = new Deflater();
    String Original_string = "This is Delftstack ", repeated_string = "";
    // Generate a repeated string
    for (int i = 0; i < 5; i++) {
      repeated_string += Original_string;
    }
    // Convert the repeated string into bytes to set the input for the deflator
    new_deflater.setInput(repeated_string.getBytes("UTF-8"));
    new_deflater.finish();
    // Generating the output in bytes
    byte compressed_string[] = new byte[1024];
    // Storing the compressed string data in compressed_string. the size for compressed string will
    // be 13
    int compressed_size = new_deflater.deflate(compressed_string, 5, 15, Deflater.FULL_FLUSH);
    // The compressed String
    System.out.println("The Compressed String Output: " + new String(compressed_string)
        + "\n Size: " + compressed_size);
    // The Original String
    System.out.println("The Original Repeated String: " + repeated_string
        + "\n Size: " + repeated_string.length());
    new_deflater.end();
  }
}

上面的代码使用 deflater 来设置转换为字节的字符串的输入并对其进行压缩。

输出:

The Compressed String Output: xœ
ÉÈ,V
Size: 15
The Original Repeated String: This is Delftstack This is Delftstack This is Delftstack This is Delftstack This is Delftstack
Size: 95