实现说明
除了类 Main,文件里再无其他定义。
try-with-resources 保证即使方法体抛出,声明的资源也会被关闭。
使用要点
- 演示输出是带标签的(
merged:、chain:),每个操作都会留下自己的一行标注。
常见问题
运行「SequenceInputStream 串联流」会打印什么?
整个文件跑完,输出行以 merged:、chain: 这类前缀开头。
核心语句
InputStream header = new ByteArrayInputStream("header\n".getBytes());
InputStream body = new ByteArrayInputStream("body\n".getBytes());
代码示例
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.Collections;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
InputStream header = new ByteArrayInputStream("header\n".getBytes());
InputStream body = new ByteArrayInputStream("body\n".getBytes());
// SequenceInputStream concatenates the streams in order
try (InputStream merged = new SequenceInputStream(header, body)) {
System.out.println("merged: " + new String(merged.readAllBytes()).replace("\n", "|"));
}
// the enumeration form chains any number of streams in order
List<InputStream> parts = List.of(
new ByteArrayInputStream("a".getBytes()),
new ByteArrayInputStream("b".getBytes()),
new ByteArrayInputStream("c".getBytes()));
try (InputStream chain = new SequenceInputStream(Collections.enumeration(parts))) {
System.out.println("chain: " + new String(chain.readAllBytes()));
}
}
}