使用Java实现对文件的切片和合并

使用Java实现对文件的切片和合并

切片

private static void cutFile() throws Exception {
        long startTime = System.currentTimeMillis();
        FileInputStream fis = null;
        FileOutputStream fos = null;
        int i = 1;
        int length = 0;
        byte[] data = new byte[1024 * 1024]; //1024 * 1024 = 1MB

        File file = new File("C:\\Users\\wjq\\Desktop\\test\\testCut.rar");
        try {
            fis = new FileInputStream(file);
            while ((length = fis.read(data)) != -1) {
                fos = new FileOutputStream("C:\\Users\\wjq\\Desktop\\test\\" + i + ".rar");
                fos.write(data, 0, length);
                logger.info("正在切分第" + i + "个文件,文件大小:" + fos.getChannel().size() / 1024 + "KB");
                fos.close();
                i++;
            }
            fis.close();
            long endTime = System.currentTimeMillis();
            logger.info("文件切分已完成,共耗时:" + (endTime - startTime) + "ms");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (!StringUtil.isEmpty(fis)) {
                fis.close();
            }
            if (!StringUtil.isEmpty(fos)) {
                fos.close();
            }
        }
    }

合并

private static void conFile() throws Exception {
        long startTime = System.currentTimeMillis();

        byte[] data = new byte[1024 * 1024]; //一次读取 1024 * 1024 = 1MB
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {

            File file = new File("C:\\Users\\wjq\\Desktop\\test\\");
            String[] listFiles = file.list();

            bos = new BufferedOutputStream(new FileOutputStream("C:\\Users\\wjq\\Desktop\\testCon.rar"));

            for (int i = 1; i <= listFiles.length; i++) {
                bis = new BufferedInputStream(new FileInputStream(new File("C:\\Users\\wjq\\Desktop\\test\\" + i + ".rar")));
                while (bis.read(data) != -1) {
                    bos.write(data);
                }
                bis.close();
                logger.info("已完成第" + i + "块文件的合并,文件大小:" + data.length / 1024 + "KB");
            }
            bos.close();
            long endTime = System.currentTimeMillis();
            logger.info("文件合并已完成,文件大小 ==> {}, 共耗时 ==> {}", new FileInputStream("C:\\Users\\wjq\\Desktop\\testCon.rar").getChannel().size() / 1024 + "KB", (endTime - startTime) + "ms");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (!StringUtil.isEmpty(bis)) {
                bis.close();
            }
            if (!StringUtil.isEmpty(bos)) {
                bos.close();
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值