把一个文件切割多份,最后再合并起来

public class MyTest2 {
    public static void main(String[] args) throws IOException {
        //把一个mp3文件切割多份,每一份是1M 最后再合并起来
        // qieGe();
        heBing();

        //合并完删除零碎的文件
        File targetFile = new File("F:\\mp3");
        File[] files = targetFile.listFiles();
        for (File file : files) {
            if (!file.getName().equals("all.mp3")) {
                file.delete();
            }
        }
        System.out.println("合并完成");

    }

    private static void heBing() throws IOException {
        File targetFile = new File("F:\\mp3");

        File[] files = targetFile.listFiles();

        Vector<FileInputStream> vector = new Vector<>();
        //遍历切割文件的文件夹,向集合中添加关联切割文件的输入流;
        for (File f : files) {
            FileInputStream fileInputStream = new FileInputStream(f);
            vector.add(fileInputStream);
        }
        //用顺序流将迭代器传入,串联所有关联分割文件的输入流;
        //迭代器遍历所有输入流里的文件,用顺序流读入文件数据,边读边写出,进而合成完整的文件;
        SequenceInputStream in = new SequenceInputStream(vector.elements());
        FileOutputStream out = new FileOutputStream(new File(targetFile, "all.mp3"));

        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = in.read(bytes)) != -1) {
            out.write(bytes, 0, len);
        }
        out.close();
        in.close();
    }

    private static void qieGe() throws IOException {
        File srcFile = new File("张学友 - 情书 .mp3");
        FileInputStream in = new FileInputStream(srcFile);

        //创建一个目标目录
        File targetFile = new File("F:\\mp3");
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        byte[] bytes = new byte[1024 * 1024];
        int len = 0;
        int j = 1;
        //每读1MB,就写出到新的文件,读完就可以分割出相同大小的不同文件;
        while ((len = in.read(bytes)) != -1) {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(targetFile, (j++) + ".mp3"));
            fileOutputStream.write(bytes, 0, len);
            fileOutputStream.close();
        }

        in.close();
    }
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值