需求:
将一个文件拆分成几个碎片文件,在将这几个碎片文件合成原文件。
主要问题:
1.合并文件的时候怎么知道原文件变成几块了?怎么知道原文件的名称和类型?
其实只要在拆分文件的时候,存储一个配置文件信息到硬盘上面,将文件变成几块和文件的名称记录在上面就好了,合并文件的时候在把这个文件读取出来,拿出其中的信息。
首先是拆分:
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file=new File("c:\\项目文件\\截图.bmp");
SplitFile(file);
}
//传入要切割的文件
private static void SplitFile(File file) throws IOException {
Properties pro=new Properties();//创建properties用来存储键值对
//用读取流关联源文件
FileInputStream fis=new FileInputStream(file);
//创建缓冲区,指定每一块文件的大小
byte[] buf=new byte[1024*1024];
//创建输出流
FileOutputStream fo=null;
//指定要放到的文件夹
File dir=new File("c:\\part");
//健壮性判断,如果不存在,创建多级目录
if(!dir.exists()){
dir.mkdirs();
}
int len=0;
//计数器,用来记录碎块数
int count=1;
while((len=fis.read(buf))!=-1){
fo=new FileOutputStream(new File(dir,(count++)+".part"));//实例化输出流,并将目的文件传给构造函数,每个块名称不同
fo.write(buf,0,len);//写入
fo.close();//每次写入完毕,关闭流
}
fo=new FileOutputStream(new File(dir, "my.properties"));//输出流,将目的文件传给它
//将被切割文件的信息保存到pro集合中。
pro.setProperty("count", count+"");
pro.setProperty("name", file.getName());
//使用store方法存储到硬盘中
pro.store(fo, "pei zhi info");
fis.close();
fo.close();
}
运行:
图片被分成5快,并且配置信息里面存入了count和name。
然后是合并:
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//MergeDemo(null);
File file=new File("c:\\part");
MergeDemo2(file);
}
private static void MergeDemo2(File dir) throws IOException {
//取出配置文件信息,通过过滤器将properties文件取出,过滤器自己写一下即可==========
File[] files=dir.listFiles(new SuffixFilter(".properties"));
//如果不是一个配置文件,抛出异常。
if(files.length!=1){
throw new RuntimeException(dir+"该目录下的propertises不合规");
}
//取出
File confile=files[0];
//获取文件中的信息==========
FileInputStream fi=new FileInputStream(confile);
Properties properties=new Properties();
//load方法,将读取流中的信息存入properties
properties.load(fi);
//取出配置文件中切割文件的个数和源文件的名称
int count=Integer.parseInt(properties.getProperty("count"));
String filename=properties.getProperty("name");
//做一个健壮性判断,取出目录中所有的碎片文件,若客户少下载了文件,则要提醒
File[] partFiles=dir.listFiles(new SuffixFilter(".part"));
if(partFiles.length!=count-1){
throw new RuntimeException("文件丢失");
}
//合并所有的碎片文件,将它和流对象关联并存储到集合当中==========
ArrayList<FileInputStream> a1=new ArrayList<FileInputStream>();
for(int x=1;x<=count-1;x++){
a1.add(new FileInputStream(new File(dir,x+".part")));
}
//拿到枚举,传给序列流
Enumeration<FileInputStream> enumeration=Collections.enumeration(a1);
//创建序列流,将多个流合并为一个序列流
SequenceInputStream sis=new SequenceInputStream(enumeration);
FileOutputStream fo=new FileOutputStream(new File(dir,filename));
byte[] b=new byte[1024*1024];
int len=0;
//只要序列流读取不返回-1,就将它写入到输出流指定文件
while((len=sis.read(b))!=-1){
fo.write(b,0,len);
}
sis.close();fo.close();
}
运行完毕:
重新变成了一个文件,即截图.bmp