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

时间:2022-10-12 09:34:57

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();
        }
    }