合并文件(序列流)

本文提供了一个使用Java进行文件合并的具体示例。通过SequenceInputStream将多个输入流按顺序连接起来,并将其内容写入到一个输出文件中。这种方法适用于需要将多个小文件合并成一个大文件的情况。

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();
}

}

转载于:https://www.cnblogs.com/future-zmy/p/6144714.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值