java Inputstream 写入到多个文件中
时间: 2024-02-23 22:59:29 浏览: 154
可以使用 Java 中的 SequenceInputStream 和 FileOutputStream 类来将一个 InputStream 对象写入到多个文件中。
首先,你需要创建多个 FileOutputStream 对象来表示输出到的多个文件:
```java
FileOutputStream out1 = new FileOutputStream("file1.txt");
FileOutputStream out2 = new FileOutputStream("file2.txt");
FileOutputStream out3 = new FileOutputStream("file3.txt");
```
接下来,你需要创建一个 InputStream 对象,将需要写入的内容写入到这个对象中:
```java
InputStream in = new FileInputStream("input.txt");
```
然后,你可以使用 SequenceInputStream 类将输入流和输出流连接起来:
```java
SequenceInputStream seqIn = new SequenceInputStream(in, new SequenceInputStream(out1, new SequenceInputStream(out2, out3)));
```
最后,你可以使用一个 while 循环将 SequenceInputStream 对象中的数据写入到每个 FileOutputStream 对象中:
```java
int data;
while ((data = seqIn.read()) != -1) {
out1.write(data);
out2.write(data);
out3.write(data);
}
```
记得在使用完毕后关闭所有的流对象,可以使用 try-with-resources 语句来自动关闭流对象:
```java
try (InputStream in = new FileInputStream("input.txt");
FileOutputStream out1 = new FileOutputStream("file1.txt");
FileOutputStream out2 = new FileOutputStream("file2.txt");
FileOutputStream out3 = new FileOutputStream("file3.txt");
SequenceInputStream seqIn = new SequenceInputStream(in, new SequenceInputStream(out1, new SequenceInputStream(out2, out3)))) {
int data;
while ((data = seqIn.read()) != -1) {
out1.write(data);
out2.write(data);
out3.write(data);
}
} catch (IOException e) {
// 处理异常
}
```
阅读全文