本帖最后由 谭立文 于 2012-9-28 14:45 编辑
package com.wenfengkeji.io;
import java.io.*;
import java.util.*;
public class FileSplit
{
public static void main(String[] args) throws IOException
{
uniteFile();
// fileSplit();
}
public static void uniteFile() throws IOException
{
ArrayList<FileInputStream> al = new ArrayList<FileInputStream>();
int partSize = 4;
for(int i = 1; i <= partSize; i++)
{
al.add(new FileInputStream("d:/test/" + i + ".part"));
}
final Iterator it = al.iterator();
Enumeration en = new MyEnumeration(it);
SequenceInputStream sis = new SequenceInputStream(en);
byte[] buf = new byte[1024 * 1024];
int len = -1;
FileOutputStream fos = new FileOutputStream("d:/test/0.mp3");
while((len = sis.read(buf))!=-1)
{
fos.write(buf, 0, len);
}
sis.close();
fos.close();
}
public static class MyEnumeration<E> implements Enumeration<Object>
{
private Iterator<E> it;
public MyEnumeration(Iterator<E> it)
{
this.it = it;
}
@Override
public boolean hasMoreElements() {
return it.hasNext();
}
@Override
public Object nextElement() {
return it.next();
}
}
//相当于就是自己实现了Enumeration接口,然后根据Iterator把数据迭代出来
public static void fileSplit()
{
FileInputStream fis = null;
FileOutputStream fos = null;
try
{
fis = new FileInputStream("d:/test/亲爱的小孩.mp3");
byte[] buf = new byte[1024 * 1024];
int len = -1;
int count = 1;
while((len = fis.read(buf))!=-1)
{
fos = new FileOutputStream("d:/test/" + count + ".part");
fos.write(buf,0,len);
fos.close();
count++;
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}finally
{
try
{
if(fos != null)
{
fos.close();
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}finally
{
try
{
if(fis != null)
{
fis.close();
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
}
}
}
|