曾梦垚

导航

合并文件(序列流)

public class Demo3 {


public static void main(String[] args) throws IOException {
testMerge();

}

public static void testMerge() throws IOException{
//1.获取目标文件
File file1 = new File("C:\\B\\a.txt");
File file2 = new File("C:\\B\\b.txt");
File file3 = new File("C:\\B\\c.txt");

//2.创建通道
FileInputStream inputStream1 = new FileInputStream(file1);
FileInputStream inputStream2 = new FileInputStream(file2);
FileOutputStream outputStream = new FileOutputStream(file3);

/*//3.用集合存输入流
ArrayList<FileInputStream> list = new ArrayList<FileInputStream>();
list.add(inputStream1);
list.add(inputStream2);

//4.边读边写
byte[] b = new byte[1024];
int length = 0;
for(int i = 0;i<list.size();i++){
while((length = list.get(i).read(b)) !=-1){
//写数据
outputStream.write(b,0,length);
}
}
//5.关闭
outputStream.close();
inputStream1.close();
inputStream2.close();*/



//3.建立一个序列流
SequenceInputStream serInputStream = new SequenceInputStream(inputStream1,inputStream2);
byte[] b = new byte[1024];

//4.读取数据
int length = 0;
while ((length = serInputStream.read(b)) != -1) {
//写入数据
outputStream.write(b,0,length);
}
//5.关闭
outputStream.close();
serInputStream.close();
}

}

posted on 2016-12-10 11:55  曾梦垚  阅读(125)  评论(0编辑  收藏  举报