Java学习之拆分与合并文件
在实际开发中有时会需要将大数据文件拆分成多个文件进行传输。传输完后又需要将拆分后 的文件合并成一个文件进行使用。这时就需要使用合并流对象 SequeceInputStream对象了。
SequeceInputStream:这个对象也是InputStream子类中的一员,它可以将多个InputStream流对象进行逻辑串联。它从输入流的有序集合开始,并从第一个输入流开始读取,直到到达文件末尾,接着从第二个输入流读取,依次类推,直到到达包含的最后一个输入流的文件末尾为止。
下面是一个例子。使用Java中的流对象对一个视频文件进行先拆分在合并。在电脑中有一个f:\\flash\\flash.avi文件,其大小为17.78M。
import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.SequenceInputStream; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; /** * 使用java中的IO对文件进行拆分与合并。 * @author Administrator * */ public class SplitAndUniteFile { private static int count=1;//定义一个户数器。一记录将文件共拆分了多少份。 /** * @param args */ public static void main(String[] args) { //拆分文件 splitFile(); //合并文件 uniteFile(); } /** * 拆分文件,使用字节流将文件拆分为多个文件。 */ public static void splitFile() { FileInputStream fis=null; FileOutputStream fos=null; try { fis=new FileInputStream("f:\\flash\\flash.avi"); byte[] b=new byte[1024*1024*5];//平均一次写入5M数据。 int len=-1; while((len=fis.read(b))!=-1) { fos=new FileOutputStream("f:\\flash\\"+(count++)+".part"); fos.write(b,0,len); fos.close(); } }catch (Exception e) { throw new RuntimeException(e); } finally { if(fos!=null) { try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(fis!=null) { try { fis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * 合并文件 */ public static void uniteFile() { ArrayList<FileInputStream> al=new ArrayList<FileInputStream>(); try{ for(int i=1;i<=count;i++) { al.add(new FileInputStream("f:\\flash\\"+i+".part")); } } catch (Exception e) { throw new RuntimeException(e); } final Iterator<FileInputStream> it=al.iterator(); Enumeration<FileInputStream> an=new Enumeration<FileInputStream>() { @Override public boolean hasMoreElements() { return it.hasNext(); } @Override public FileInputStream nextElement() { return it.next(); } }; //将多个FileInputStrema对象合并到SequenceInputStream中 SequenceInputStream sis=new SequenceInputStream(an); BufferedOutputStream bos=null; try{ bos=new BufferedOutputStream(new FileOutputStream("f:\\flash.avi")); byte b[]=new byte[1024]; int len=-1; while((len=sis.read(b))!=-1) { bos.write(b, 0, len); } }catch (Exception e) { throw new RuntimeException(e); } finally { if(sis!=null) { try { sis.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(bos!=null) { try { bos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
在合并文件后查看文件大小,还是17.78M,说明没有损失数据。打开文件能正常播放。