《黑马程序员》 合并流之文件切割与合并的工具类

来源:互联网 发布:ajax提交返回json 编辑:程序博客网 时间:2024/04/24 07:54
class FileUtils {/*   文件的切割与合并的工具类*/public static void main(String[] args) {File file=new File("c:\\test.avi");File srcDir;File dFile;try{//split(file);srcDir=new File("c:\\temp");dFile=new File("c:\\temp\\temp.avi");merge(srcDir,dFile);}catch(Exception e){e.printStackTrace();}}//将分割的文件进行合并//需要传递指定的目录,和合并后的文件的对象public static void merge(File dir,File dFile) throws IOException{//Vector它虽然是可以获取enumeration但是速度太慢//使用arraylist效率会高一些ArrayList<FileInputStream> al=new ArrayList<FileInputStream>();for(int x=1;x<=getPartCount(dir);x++){//创建与之对应的流对象al.add(new FileInputStream("c:\\temp\\temp"+x+".part"));}//arraylist中没有enumeration.它有iterator//我们可以自己来实现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);//我们来读取数据并且进行操作byte[] buff=new byte[1024];int len=0;FileOutputStream fos=new FileOutputStream(dFile);while((len=sis.read(buff))!=-1){fos.write(buff,0,len);}fos.close();sis.close();}//获取指定目录下的part切割文件的数量public static int getPartCount(File dir) throws IOException{ArrayList<File> list=new ArrayList<File>();if(dir.isDirectory()){//如果是目录则执行该动作File[] files=dir.listFiles();for(File file:files){if(file.isDirectory()){getPartCount(file);}else{//获取part文件的数量if(file.getName().endsWith(".part")){list.add(file);}}}}    return list.size();  //否则直接返回0}    //文件切割的方法public static void split(File sFile) throws IOException{//使用流和文件相关联FileInputStream fis=new FileInputStream(sFile);//文件输出流FileOutputStream fos=null;//新建一个大小为1MB的缓存byte[] buffer=new byte[1024*1024];int len=0; //记录读取的文件的个数int count=1;  //用于文件名的计数while((len=fis.read(buffer))!=-1){fos=new FileOutputStream(new File("c:\\temp"+(count++)+".part"));fos.write(buffer,0,len);  //把数据写入到文件中fos.close();  //关闭流}fis.close();}}

0 0