/*
分割合并小文件
在c盘先手动粘贴一个jpg文件,大概2.5M大小,便于观察
在c盘手动建立一个文件夹splits,用于存放分割后的文件
这个图片文件将被分成3块:(1M ,1M , 0.5M) 大小
本例中有很多细节方面没写,只有大致的功能实现过程
异常也直接抛了
[示例]:分割合并文件
*/
import java.io.*;
import java.util.*;
class Demo
{
public static void main(String[] args) throws IOException
{
splitFile();//分割
merger(); //合并文件
}
public static void merger() throws IOException //合并文件
{
ArrayList<FileInputStream> al =new ArrayList<FileInputStream>();
for(int x=1;x<=3;x++)
{
al.add(new FileInputStream("c:\\splits\\"+x+".part")); //有3个part文件要合并
}
final Iterator<FileInputStream> it = al.iterator();
Enumeration<FileInputStream> en = //实现枚举器
new Enumeration<FileInputStream>()
{
public boolean hasMoreElements()
{
return it.hasNext();
}
public FileInputStream nextElement() //返回迭代的下一个枚举器中的元素
{
return it.next();
}
};
SequenceInputStream sis = new SequenceInputStream(en); //流串联器
FileOutputStream fos = new FileOutputStream("c:\\splits\\all.jpg");
byte[] buf = new byte[1024*1024]; //1M空间的数组
int len = 0;
while(true)
{
len = sis.read(buf);
if(len!=-1)
{
fos.write(buf,0,len);
}
else
{
break;
}
}
fos.close();
sis.close();
}
public static void splitFile() throws IOException //分割文件
{
FileInputStream fis = new FileInputStream("c:\\m.jpg");
FileOutputStream fos = null;
byte[] buf = new byte[1024*1024];
int len =0;
int partCount =0; //块数
while(true)
{
len=fis.read(buf);
if(len!=-1)
{
partCount++;
fos = new FileOutputStream("c:\\splits\\"+partCount+".part");
fos.write(buf,0,len);
fos.close();
}
else
{
break;
}
}
fis.close();
}
}