在 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
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。