基础知识之----------IO流(4)操作文件

1、文件的切割合并

  

public class SpliFileDemo {

    //创建1M的缓冲区
    private static int SIZE=1048576;

    public static void main(String[] args) throws IOException {
        File file=new File("c://partfile");
//        splitFile(file);
        mergeFile(file);
    }

    public static void splitFile(File file) throws IOException{

        //用流读取文件
        FileInputStream fis=new FileInputStream(file);

        //定义一个1M的缓冲区
        byte[] buf=new byte[SIZE];

        FileOutputStream fos=null;

        int len=0;

        int count=1;

        File dir=new File("c:\\partfile");

        if (!dir.exists())
            dir.mkdirs();

        while ((len=fis.read(buf))!=-1){
            fos=new FileOutputStream(new File(dir,(count++)+".part"));
            fos.write(buf,0,len);
        }

        fos.close();

        fis.close();

    }

    public  static void mergeFile(File dir) throws IOException {

        ArrayList<FileInputStream> a1=new ArrayList<FileInputStream>();

        for (int x=1;x<=7;x++) {
            a1.add(new FileInputStream(new File(dir, x + ".part")));
        }
            Enumeration<FileInputStream> en=Collections.enumeration(a1);

            SequenceInputStream sis=new SequenceInputStream(en);

            FileOutputStream fos=new FileOutputStream(new File(dir,"sss1.pdf"));

            byte[] buf=new byte[1024*1024];

            int len=0;

            while((len=sis.read(buf))!=-1){
                fos.write(buf,0,len);
            }

            fos.close();

            sis.close();
        }
    }

 

posted @ 2018-03-01 19:30  张小铁  阅读(127)  评论(0编辑  收藏  举报