我正在尝试解压缩已作为字符串读入内存的 gzip 文件内容。
/**
* Read file content into a String
*/
private static String readUsingFileInputStream(String fileName) {
FileInputStream fis = null;
byte[] buffer = new byte[10];
StringBuilder sb = new StringBuilder();
try {
fis = new FileInputStream(fileName);
while (fis.read(buffer) != -1) {
sb.append(new String(buffer));
buffer = new byte[10];
}
fis.close();
} catch (IOException e) {
//...
return sb.toString();
}
/**
* Unzip file content
*/
public static String unzip(final byte[] compressed) {
try (final GZIPInputStream gzipInput = new GZIPInputStream(new ByteArrayInputStream(compressed));
final StringWriter stringWriter = new StringWriter()) {
IOUtils.copy(gzipInput, stringWriter, UTF_8);
return stringWriter.toString();
} catch (IOException e) {
throw new UncheckedIOException("Error while decompression!", e);
}
}
然后在我的
main
方法中,我正在做:
String compressedData = readUsingFileInputStream("/path/to/my/compressed_file_json.gz");
System.out.println(unzip(compressedData.getBytes(UTF_8)));
但是我收到以下错误:
java.util.zip.ZipException: Not in GZIP format
at java.base/java.util.zip.GZIPInputStream.readHeader(GZIPInputStream.java:166)
at java.base/java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:80)
at java.base/java.util.zip.GZIPInputStream.<init>(GZIPInputStream.java:92)
我做错了什么?我已经验证该文件实际上是 GZIP 格式并且没有损坏。
注意:我知道我可以直接在 GZIPInputStream 中输入 FileInputStream,但出于实际问题的目的,我无法访问 FileInputStream,只是生成字符串。
“...我做错了什么?我已经验证该文件实际上是 GZIP 格式并且没有损坏。...”
从 readUsingFileInputStream 返回一个 字节数组,并使用 String 构造函数 创建一个 UTF-8 值。
/**
* Read file content into a String
*/
private static byte[] readUsingFileInputStream(String fileName) throws IOException {
try (FileInputStream fis = new FileInputStream(fileName)) {
return fis.readAllBytes();
}
}
/**
* Unzip file content
*/
public static String unzip(final byte[] compressed) throws IOException {
try (final GZIPInputStream gzipInput = new GZIPInputStream(new ByteArrayInputStream(compressed))) {
return new String(gzipInput.readAllBytes(), StandardCharsets.UTF_8);
}
}
示例
byte[] compressedData = readUsingFileInputStream("/path/to/my/compressed_file_json.gz");
System.out.println(unzip(compressedData));