欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Java实现视频分割和合并:将大文件拆分成多个小文件并将其重新组合为一个大文件

最编程 2024-08-03 18:58:33
...

今天闲着没事写一个小的测试,就是写了一个视频的拆分,我是把一个文件拆分为多个txt文件保存,然后再把多个txt文件合并为一个视频并播放(这也是断点续传的一部分吧)

一个文件拆分为多个文件的代码的测试:

@Test
    public void test1()  {
        File oldfile = new File("D:/视频/"+"1.mp4");
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
            try {
                fileInputStream = new FileInputStream(oldfile);
                int num=1;
                byte[] aByte = new byte[153310];
                int length=0;
                while ((length=fileInputStream.read(aByte)) != -1 ) {
                    fileOutputStream = new FileOutputStream("D:/视频/"+num+".txt");
                    fileOutputStream.write(aByte,0,length);
                    num++;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

这面这个的话我是一次153310字节保存到一个txt文件的,这样写肯定是不太好,但是我本来想用读取1024然后一点点追加到文件,奈何我没想到实现,这种应该可以用在while循环里面然后取出文件,用文件大小比较字节,然后不够字节的话进行追加,大伙可以想一想怎么实现的的.

 上面的1.mp4是原始文件,txt文件就是拆分之后出现的文件

然后对文件进行合并

@Test
    public void test2()  {
        File newfile = new File("D:/视频/"+"2.mp4");
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        for (int i = 1; i <=10; i++) {
            File subfile= new File("D:/视频/"+i+".txt");
            try {
                fileInputStream=new FileInputStream(subfile);
                fileOutputStream = new FileOutputStream(newfile,true);
                byte[] aByte = new byte[1024];
                int length=0;
                while ((length=fileInputStream.read(aByte)) != -1 ) {
                    fileOutputStream.write(aByte,0,length);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

也是可以播放的