【java编程】IO流之切割流和另一种合并流方法

来源:互联网 发布:什么是网络攻防大赛 编辑:程序博客网 时间:2024/05/17 05:17
import java.io.*;import java.util.*;class SplitAndMerge {public static void main(String[] args) throws IOException{MegerInputStream();}//切割流public static void SplitOutputStream() throws IOException{//创建文件对象File file=new File("d:\\1.jpg");//创建字节输入流FileInputStream fis=new FileInputStream(file);//创建字节输出流FileOutputStream fos=null;//创建缓冲区byte[] buf=new byte[1024*512];int len=0;//定义计数器int count=1;while((len=fis.read(buf))!=-1){//创建一个字节输出流,当存满缓冲区后,再创建另一个字节输出流 fos=new FileOutputStream("a."+"part"+(count++));fos.write(buf,0,len);fos.close();}fis.close();}//合并流:用SequenceInputStream的构造方法Enumeration枚举来接收多个字节流//因为Vector集合方法效率低,所以,用ArrayList集合代替Vector集合。//替代的方法是:复写Enumeration方法的hasMoreElements()方法和nextElement()方法    public static void MegerInputStream() throws IOException{//创建ArrayList集合ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();//将四个流对象加入到集合中for(int x=1;x<5;x++){al.add(new FileInputStream("a.part"+x));}//创建Inerator迭代器 Iterator<FileInputStream> it=al.iterator();//复写Enumeration枚举对象Enumeration<FileInputStream> en=new Enumeration<FileInputStream>(){public boolean hasMoreElements(){return it.hasNext();}public FileInputStream nextElement(){return it.next();}};//创建SequenceInputStream对象SequenceInputStream sis=new SequenceInputStream(en);//创建字节输出流FileOutputStream fos=new FileOutputStream("b.jpg");byte[] buf=new byte[1024*512];int len=0;while((len=sis.read(buf))!=-1){fos.write(buf,0,len);}sis.close();fos.close();}}

0 0
原创粉丝点击