java SequenceInputStream 序列流

一、需求

将一首mp3切割后再合并。


二、代码

public class Main
{
    public static void main(String[] args) throws IOException
    {
        spilt();
        merge();
    }
    static void spilt() throws IOException
    {
        //源文件
        File file = new File("/Users/yao/Music/","生活不止眼前的苟且.mp3");
        //目标文件夹
        File dir = new File("/Users/yao/Music/");
        //建立数据通道
        FileInputStream fileInputStream = new FileInputStream(file); 
        //建立缓冲数组读取
        byte[] buff = new byte[1024*1024];  //切割后,每个文件大小为1M
        int length = 0;
        for(int i = 1 ; (length = fileInputStream.read(buff))!=-1 ; i++)
        {
            FileOutputStream fileOutputStream = new FileOutputStream(new File(dir,file.getName()+"_part"+i+"_.mp3"));
            fileOutputStream.write(buff, 0, length);
            fileOutputStream.close();
        }
        fileInputStream.close();
    }
    static void merge() throws IOException
    {
        //找到目标文件
        File dir = new File("/Users/yao/Music/");
        File[] files = dir.listFiles();
        //通过目标文件夹找到所有的MP3文件,然后把所有的_.mp3文件添加到vector中。
        Vector<FileInputStream> vector = new Vector<FileInputStream>();
        for(File f : files)
        {
            if(f.getName().endsWith("_.mp3"))
            {
                vector.add(new FileInputStream(f));
            }
        }
        //通过Vector获取迭代器
        Enumeration<FileInputStream> e = vector.elements();
        //创建序列流
        SequenceInputStream inputStream = new SequenceInputStream(e);
        //建立文件的输出通道
        FileOutputStream fileOutputStream = new FileOutputStream("/Users/yao/Music/合并.mp3");
        //建立缓冲数组读取文件
        byte[] buf = new byte[1024];
        int length = 0 ; 
        while((length =  inputStream.read(buf))!=-1){
            fileOutputStream.write(buf,0,length);
        }
        //关闭资源
        fileOutputStream.close();
        inputStream.close();
    }
}

三、运行截图

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值