在Java中,如何在不去文件系统的情况下解压字符串?
所需:在Java中,如何在不去文件系统的情况下解压字符串?,java,gzip,gzipinputstream,gzipoutputstream,Java,Gzip,Gzipinputstream,Gzipoutputstream,所需: 创建压缩和解压缩字符串或字节数组。 之后,我计划对其进行Base64编码,以便写入日志文件 不幸的是,它似乎没有意识到它正在被压缩或其他什么。 我假设它缺少一些元数据字节,但找不到我需要的 输出: 测试类: import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.GZIPInputStream;
创建压缩和解压缩字符串或字节数组。 之后,我计划对其进行Base64编码,以便写入日志文件 不幸的是,它似乎没有意识到它正在被压缩或其他什么。 我假设它缺少一些元数据字节,但找不到我需要的 输出: 测试类:
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;
public class TestEncodeDecode {
private static final String UTF_8 = "UTF-8";
public static void main(String[] args) throws IOException {
String originalString = " This online sample demonstrates functionality of a base64 property, ByteArray class and Huge asp file upload.\n The sample uses a special Base64 algorithm written for the ByteArray class.";
System.out.println(originalString);
System.out.println("------------------------------------------------------");
String compressedString = compressString(originalString);
System.out.println(compressedString);
System.out.println("------------------------------------------------------");
String uncompressedString = uncompressString(compressedString);
System.out.println(uncompressedString);
Validate.isTrue(originalString.equals(uncompressedString));
}
public static String compressString(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
byte[] bytes = str.getBytes(UTF_8);
ByteArrayOutputStream out = new ByteArrayOutputStream(bytes.length);
GZIPOutputStream gzip = new GZIPOutputStream(out);
gzip.write(bytes);
gzip.flush();
gzip.close(); //Finalizes the ByteArrayOutputStream's value
String compressedString = out.toString(UTF_8);
return compressedString;
}
public static String uncompressString(String str) throws IOException {
if (str == null || str.length() == 0) {
return str;
}
ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes(UTF_8));
GZIPInputStream gzip = new GZIPInputStream(in);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1000];
int len;
while ((len = in.read(b)) > 0) {
out.write(b, 0, len);
}
gzip.close();
out.close();
String uncompressedString = out.toString(UTF_8);
return uncompressedString;
}
}
首先,gzip数据不一定是UTF-8编码的文本。不要使用
String
作为中介,请使用byte[]
。其次,您正在从中的读取,而不是从解压字符串
方法中的gzip
读取。使用正确的流并使用byte[]修复了Thank Sotirios的可能重复。首先,gzip数据不一定是UTF-8编码文本。不要使用String
作为中介,请使用byte[]
。其次,您正在从
中的读取,而不是从解压字符串
方法中的gzip
读取。使用正确的流并使用byte[]修复了Thank Sotirios的可能重复。