我尝试使用 DeflaterOutputStream 压缩字符串并使用 base64 转换输出以将结果保存在另一个字符串中
public static String compress(String str) throws IOException {
byte[] data = str.getBytes("UTF-8");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
java.util.zip.Deflater compresser = new java.util.zip.Deflater(java.util.zip.Deflater.BEST_COMPRESSION, true);
DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, cozmpresser);
deflaterOutputStream.write(data);
deflaterOutputStream.close();
byte[] output = stream.toByteArray();
return Base64Coder.encodeLines(output);
}
现在我想试试 ZipOutputStream。我试过了
public static String compress(String str) throws IOException {
byte[] data = str.getBytes("UTF-8");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ZipOutputStream deflaterOutputStream = new ZipOutputStream(stream);
deflaterOutputStream.setMethod(ZipOutputStream.DEFLATED);
deflaterOutputStream.setLevel(8);
deflaterOutputStream.write(data);
deflaterOutputStream.close();
byte[] output = stream.toByteArray();
return Base64Coder.encodeLines(output);
}
但不工作。ZipOutputStream 似乎面向文件夹和文件的结构,我该怎么办?