在 Java 中壓縮字串

Sheeraz Gul 2022年4月27日
在 Java 中壓縮字串

當我們想要節省記憶體時,需要壓縮字串。在 Java 中,deflater 用於以位元組為單位壓縮字串。

本教程將演示如何在 Java 中壓縮字串。

在 Java 中使用 deflater 壓縮字串

deflater 是 Java 中的物件建立器,它壓縮輸入資料並用壓縮資料填充指定的緩衝區。

例子:

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

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
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相關文章 - Java String