在Java中,可以使用java.util.zip
包中的Deflater
和Inflater
类来进行字符串的压缩和解压缩操作。以下是一个简单的示例代码:
import java.util.zip.Deflater;
import java.util.zip.Inflater;
public class Main {
public static byte[] compressString(String input) {
try {
byte[] inputBytes = input.getBytes();
Deflater deflater = new Deflater();
deflater.setInput(inputBytes);
deflater.finish();
byte[] outputBytes = new byte[inputBytes.length];
int compressedSize = deflater.deflate(outputBytes);
byte[] compressedBytes = new byte[compressedSize];
System.arraycopy(outputBytes, 0, compressedBytes, 0, compressedSize);
return compressedBytes;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String decompressString(byte[] input) {
try {
Inflater inflater = new Inflater();
inflater.setInput(input);
byte[] outputBytes = new byte[input.length];
int decompressedSize = inflater.inflate(outputBytes);
byte[] decompressedBytes = new byte[decompressedSize];
System.arraycopy(outputBytes, 0, decompressedBytes, 0, decompressedSize);
return new String(decompressedBytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
String input = "Hello, this is a test string for compression.";
byte[] compressedData = compressString(input);
String decompressedData = decompressString(compressedData);
System.out.println("Original data: " + input);
System.out.println("Compressed data: " + new String(compressedData));
System.out.println("Decompressed data: " + decompressedData);
}
}
在上面的示例中,compressString
方法用于压缩输入的字符串,而decompressString
方法用于解压缩输入的字节数组。通过这两个方法,可以实现字符串的压缩和解压缩操作。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/966082.html