您的位置:首页 > 产品设计 > UI/UE

IO流--SequenceInputStream序列化流的应用--文件合并

2013-12-10 22:25 239 查看
package cn.itheima.cway.IO;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.SequenceInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;

public class MergerFile {

/**需求:合并文件
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// 指定待合并文件的目录
File file=new File("F:\\ss");
mergerFile(file);

}
/**
* 功能:将part文件合并为一个文件
* 思路:
* 	1、需要读取part临时文件中的内容,所以,需要集合:ArrayList
* 	2、既然有读取,则需要文件读取流:FileInputStream
* 	3、既然是需要合并文件,则需要SequenceInputsteam
* 	4、最后需要把集合中的内容输出到一个文件,则需要输出流:FileOutputStream
* @param dec
* @throws IOException
*/

public static void mergerFile(File dec) throws IOException
{
//创建一个集合,用于存放读取到的part文件内容
ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();

//将part文件读取到集合中
for(int i=1;i<=4;i++)
{
al.add(new FileInputStream(new File(dec,i+".part")));
}

//合并后的文件名:
File dir=new File(dec,"B.mp3");
if(!dir.exists())
dir.createNewFile();

//把集合中的元素转换为枚举
Enumeration<FileInputStream> en=Collections.enumeration(al);

//创建序列化输入流,去读取part文件(碎片文件)的内容
SequenceInputStream	 sis=new SequenceInputStream(en);

//创建一个输出流,用于保存合并后的文件内容
FileOutputStream fos=new FileOutputStream(dir);

int len=0;
byte[] buf=new byte[1024];

while((len=sis.read(buf))!=-1)
{
fos.write(buf,0,len);

}

fos.close();
sis.close();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: