在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
方法用于解壓縮輸入的字節數組。通過這兩個方法,可以實現字符串的壓縮和解壓縮操作。