java将字符串压缩很短成字符串并能解压缩还原的工具类
时间: 2023-09-12 13:06:35 浏览: 312
Java中字符串生成图片工具类
可以使用Java中的GZIP进行字符串的压缩和解压缩,以下是示例代码:
将字符串压缩为短字符串:
```java
import java.io.*;
import java.util.Base64;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GzipUtils {
public static String compress(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes());
gzip.close();
return Base64.getEncoder().encodeToString(out.toByteArray());
}
public static String uncompress(String compressedStr) throws IOException {
if (compressedStr == null || compressedStr.length() == 0) {
return compressedStr;
}
byte[] compressed = Base64.getDecoder().decode(compressedStr);
ByteArrayInputStream in = new ByteArrayInputStream(compressed);
GZIPInputStream gzip = new GZIPInputStream(in);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = gzip.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
gzip.close();
out.close();
return out.toString();
}
}
```
使用示例:
```java
String originalString = "Hello, World!";
String compressedString = GzipUtils.compress(originalString);
String decompressedString = GzipUtils.uncompress(compressedString);
System.out.println(originalString.equals(decompressedString)); // true
```
注意:压缩后的字符串长度取决于原始字符串的内容和长度,不一定一定能够压缩得很短。
阅读全文