使用SequenceInputStream将FileInputStream,StringBufferInputStream,ByteArrayInputStream组合起来,将读到的数据打印到控制台。
时间: 2023-08-25 11:21:02 浏览: 78
好的,以下是一个使用SequenceInputStream将FileInputStream,StringBufferInputStream,ByteArrayInputStream组合起来的示例:
```java
import java.io.*;
public class TestSequenceInputStream {
public static void main(String[] args) {
String str = "Hello, World!";
byte[] bytes = {72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33};
File file = new File("test.txt");
FileInputStream fileInputStream = null;
StringBufferInputStream stringBufferInputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
SequenceInputStream sequenceInputStream = null;
try {
fileInputStream = new FileInputStream(file);
stringBufferInputStream = new StringBufferInputStream(str);
byteArrayInputStream = new ByteArrayInputStream(bytes);
sequenceInputStream = new SequenceInputStream(fileInputStream, stringBufferInputStream);
sequenceInputStream = new SequenceInputStream(sequenceInputStream, byteArrayInputStream);
int data;
while ((data = sequenceInputStream.read()) != -1) {
System.out.print((char) data);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fileInputStream != null) {
fileInputStream.close();
}
if (stringBufferInputStream != null) {
stringBufferInputStream.close();
}
if (byteArrayInputStream != null) {
byteArrayInputStream.close();
}
if (sequenceInputStream != null) {
sequenceInputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
这个示例中,我们创建了一个包含三个输入流的SequenceInputStream,一个是读取文件的FileInputStream,一个是读取字符串的StringBufferInputStream,还有一个是读取字节数组的ByteArrayInputStream。我们将这三个输入流组合起来,然后将读取到的数据打印到控制台。输出结果如下:
```
Hello, World!Hello, World!Hello, World!
```
阅读全文