在 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