实现说明
底层就是类 MemberReader。
try-with-resources 保证即使方法体抛出,声明的资源也会被关闭。
使用要点
- 跑完文件,输出里会留下标记——
both reads:。
常见问题
运行「GZIPInputStream 读拼接的多 member」会打印什么?
运行文件本身,both reads: 这些前缀各对应一段演示逻辑。
核心语句
System.arraycopy(second.toByteArray(), 0, concatenated, first.size(), second.size());
System.arraycopy(first.toByteArray(), 0, concatenated, 0, first.size());
gzip.write("second member".getBytes(StandardCharsets.UTF_8));
代码示例
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class MemberReader {
public static void main(String[] args) throws Exception {
ByteArrayOutputStream first = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(first)) {
gzip.write("first member".getBytes(StandardCharsets.UTF_8));
}
ByteArrayOutputStream second = new ByteArrayOutputStream();
try (GZIPOutputStream gzip = new GZIPOutputStream(second)) {
gzip.write("second member".getBytes(StandardCharsets.UTF_8));
}
// 两段 gzip 原样拼接仍是合法流:GZIPInputStream reads concatenated members back to back
byte[] concatenated = new byte[first.size() + second.size()];
System.arraycopy(first.toByteArray(), 0, concatenated, 0, first.size());
System.arraycopy(second.toByteArray(), 0, concatenated, first.size(), second.size());
String all = new String(new GZIPInputStream(new ByteArrayInputStream(concatenated))
.readAllBytes(), StandardCharsets.UTF_8);
System.out.println("both reads: " + all);
}
}