黑马程序员技术交流社区
标题:
Java IO流之序列流
[打印本页]
作者:
theape
时间:
2016-7-22 12:25
标题:
Java IO流之序列流
package com.heima.otherio;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.SequenceInputStream;
import java.util.Enumeration;
import java.util.Vector;
public class Demo1_SequenceIS {
public static void main(String[] args) throws IOException {
String str1 = "a.txt";
String str2 = "b.txt";
String str3 = "c.txt";
String dest = "d.txt";
method0(str1,str2,dest);
method1(str1,str2,dest);
method1(str1,str2,str3,dest);
printFile(dest);
}
public static void method0(String src1,String src2,String destStr) throws IOException {
// 不使用序列流
FileInputStream fis1 = new FileInputStream(src1);
FileOutputStream fos = new FileOutputStream(destStr);
int b;
while ((b = fis1.read()) != -1) {
fos.write(b);
}
fis1.close();
FileInputStream fis2 = new FileInputStream(src2);
while((b = fis2.read()) != -1) {
fos.write(b);
}
fis2.close();
fos.close();
}
public static void method1(String src1, String src2,String destStr) throws IOException {
// 两个输入流的情况,使用序列流
FileInputStream fis1 = new FileInputStream(src1);
FileInputStream fis2 = new FileInputStream(src2);
SequenceInputStream sis = new SequenceInputStream(fis1,fis2);
FileOutputStream fos = new FileOutputStream(destStr);
int b;
while ((b=sis.read()) != -1) {
fos.write(b);
}
sis.close();
fos.close();
}
public static void method1(String src1,String src2, String src3, String destStr) throws IOException {
// 多个输入流,使用枚举,转序列流
// Enumeration<FileInputStream> en = new Enumeration();
Vector<FileInputStream> v = new Vector<>();
v.add(new FileInputStream(src1));
v.add(new FileInputStream(src2));
v.add(new FileInputStream(src3));
Enumeration<FileInputStream> en = v.elements();
SequenceInputStream sis = new SequenceInputStream(en);
FileOutputStream fos = new FileOutputStream(destStr);
int b;
while ((b = sis.read()) != -1) {
fos.write(b);
}
sis.close();
fos.close();
}
public static void printFile(String destStr) throws IOException {
// 打印目标文件的内容
BufferedReader br = new BufferedReader(new FileReader(destStr));
String s;
while ((s = br.readLine()) != null) {
System.out.println(s);
}
}
}
Demo1_SequenceIS.zip
2016-7-22 12:25 上传
点击文件名下载附件
868 Bytes, 下载次数: 17
作者:
呆呆的小呆
时间:
2016-7-22 21:58
66666666666666666666
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2