IO练习题--文件分割

题目

写一个方法,将一个文件分割为每份1MB大小的若干份,存储在一个temp的文件夹中,
然后再写一个方法,将这若干份合并为一个文件.

实现代码

public class Split_Combine {
    public static void main(String[] args) {
        File f = new File("D:\\Tule - Fearless.mp3");
        try {
            Split(f);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件找不到");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("读写异常");
        }

        File f1 = new File("E://temp");
        try {
            combain(f1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

	//文件的分割
    public static void Split(File file) throws IOException {
        if (file != null || file.exists()) { //文件是否为空,是否存在
            //创建临时文件夹
            File f = new File("E:\\temp");
            //是否存在,不存在创建
            if (!f.exists()) {
                f.mkdirs();
            }
            long size = file.length();//文件大小
            long t = 1024 * 1024;//每份大小
            long count = size % 2 == 0 ? size / t : size / t + 1;//文件个数
            //先输入一个文件
            FileInputStream in = new FileInputStream(file);
            byte[] b = new byte[1024];
            int length = 0;
            for (int i = 0; i < count; i++) {
                int sum = 0;
                FileOutputStream out = new FileOutputStream("E:\\temp\\" + (i + 1) + ".temp");
                while ((length = in.read(b)) != -1) {
                    out.write(b, 0, length);
                    sum += length;
                    if (sum >= t) {
                        break;
                    }
                }
            }
        }
    }

	//文件的合并
    public static void combain(File file) throws IOException {
        File[] fs = file.listFiles();//获取临时文件中的所有文件
        if (fs.length > 0) {
            FileOutputStream out = new FileOutputStream("D:\\Tule - Fearless1.mp3");
            for (int i = 0; i < fs.length; i++) {
                FileInputStream in = new FileInputStream("E:\\temp\\" + (i + 1) + ".temp");
                byte[] b = new byte[1024];
                int length = 0;
                while ((length = in.read(b)) != -1) {
                    out.write(b, 0, length);
                }
                in.close();
            }
            out.close();
            for (int i = 1; i < fs.length; i++) {
                fs[i].delete();
            }
            file.delete();

        }
    }
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值