如何在Java中将视频文件拆分为多个视频文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22574607/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 16:35:44  来源:igfitidea点击:

How to split a video file into multiple video files in Java

javafilesplit

提问by user3449016

I started learning about java coding and I want to split the video file, so here I obtained the code from youtube. The code split the file into parts of required mb I did some modification wanting it to split the file into required number of parts. This original code splits the file into 16 mbhere :

我开始学习java编码,我想分割视频文件,所以在这里我从youtube. 代码将文件拆分为所需 mb 的部分我做了一些修改,希望它将文件拆分为所需数量的部分。此原始代码将文件拆分为16 mb此处:

if(e==1024*1024*16) // split the file to 16 mb for each part
        {
            e =0L;
            fout.close();
            doPart();
        }

so if I put want the value in kb eg. 300kb for each part, the program just does not split the file for me.

所以如果我把想要的值放在 kb 中,例如。每个部分 300kb,程序只是没有为我拆分文件。

    package fsplit;

    import java.io.File;
    import java.io.RandomAccessFile;

    public class SplitVid {
    public static void main(String args[])
    {
        try {
            new SplitVid();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } // end main
    File f=new File("thisfile.mp4");
    long fsize = f.length()/1024; // file size in bytes
    long parts = 9; // Divide the file into how many parts?
    long fsizeOfEachinkB = fsize/parts;
    int readInt;
    RandomAccessFile fin, fout;
    byte b[] = new byte[2048];
    long e = 0L;
    int j = 1;
    public SplitVid() throws Exception
    {
        fin=new RandomAccessFile(f, "r");
        doPart();

    }

    public void doPart() throws Exception
    {
        fout = new RandomAccessFile(f.getPath() + "Part"+j++, "rw");

        while((readInt = fin.read(b))!= -1)
        {
            fout.write(b, 0, readInt);
            e+= readInt;


            **if(e==1024*fsizeOfEachinkB)//divide each file into fsize/parts per file**
            {
                e =0L;
                fout.close();
                doPart();
            }
        }
        System.out.println("The size of this file is " + f.length()/1024 + " kb");
        System.out.println("The file is divided into " + parts + " parts");
        System.out.println("Each part has " + fsizeOfEachinkB + " kb");
        fout.close();
        fin.close();
        f.delete(); // deletes the original file after the split is done

    }


} //end class

Now if I increase 'parts' until fsizeOfEachinkBis less than 1 mb, then the program just does not split the files at all. Anyone please help me looking into this ?

现在,如果我增加“部分”直到fsizeOfEachinkB小于1 mb,那么程序根本不会拆分文件。有人请帮我调查一下吗?

回答by CoderCroc

For Specific Split you have to Do following things..

对于特定拆分,您必须执行以下操作..

1]Calculate No of partitions can be made by this file.

1]计算此文件可以创建的分区数。

Means if you want every part of 300KB than...

意味着如果你想要 300KB 的每一部分都比......

calculeteParts=(long)(fsize/(300));//As fsize already in KB in your program.(FOR FILE IN MB)

2]For Making No of Parts say from file f we can make 30 patitions of Size 300KB.

2]对于从文件 f 中说的制作零件数量,我们可以制作 30 个大小为 300KB 的分区。

while((readInt = fin.read(b))!= -1)
        {

            fout.write(b, 0, readInt);
            e+= readInt;

          if(e==300*1024)//if Read 300 Upcoming KBs done 
            {
                e =0L;

                  fout.close();
                  doPart();


            }


        }

But Most importantly

但最重要的是

PROBLEM NEED TO SOLVE

需要解决的问题

Say you have A file of size 9.04MB and you want to divide it into 300KB partitions. So programmatically doing this you will have to make it multiple of 300KB.

假设您有一个大小为 9.04MB 的文件,并且您想将其划分为 300KB 的分区。因此,以编程方式执行此操作,您必须将其设为 300KB 的倍数。

Example.

例子。

9.04*1024=9256.46KB
So total of 9256KB approximately

Now Divide it with your needed size
9256/300=30.85 so approximately 30 parts.

So 0.85 will be lost

Or if you take **31**:

300*31=9300 which is greater than 9256

doParts();method called recursively so at LAST PART which MAY NOT be upto size 300KB it will read upto possible value but after that it will generate Stream Closed:IOEXceptionEventhough it doesn't matter to you.Than it's fine.

doParts();递归调用的方法,所以在最后一部分它可能不会达到 300KB 的大小,它会读取到可能的值,但之后它会生成Stream Closed:IOEXception即使对你来说无关紧要。那很好。

回答by UdayKiran Pulipati

Split the File Despicable Me 2 - Trailer (HD) - YouTube.mp4into twenty equal parts

将文件Despicable Me 2 - Trailer (HD) - YouTube.mp4分成 20 个相等的部分

Note:Paste the file Despicable Me 2 - Trailer (HD) - YouTube.mp4under Documentsfolder.

注意:将文件粘贴到文件夹Despicable Me 2 - Trailer (HD) - YouTube.mp4Documents

Example of split video file into multiple video files using java.

使用 java 将视频文件拆分为多个视频文件的示例。

Code:

代码:

package com.uk.mysqlmaven.jsf.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
 * 
 * @author uday.p
 *
 */
public class SplitVideoFile {
    public static void main(String[] args) {
        try {
            File file = new File("C:/Documents/Despicable Me 2 - Trailer (HD) - YouTube.mp4");//File read from Source folder to Split.
            if (file.exists()) {

            String videoFileName = file.getName().substring(0, file.getName().lastIndexOf(".")); // Name of the videoFile without extension
            File splitFile = new File("C:/Documents/Videos_Split/"+ videoFileName);//Destination folder to save.
            if (!splitFile.exists()) {
                splitFile.mkdirs();
                System.out.println("Directory Created -> "+ splitFile.getAbsolutePath());
            }

            int i = 01;// Files count starts from 1
            InputStream inputStream = new FileInputStream(file);
            String videoFile = splitFile.getAbsolutePath() +"/"+ String.format("%02d", i) +"_"+ file.getName();// Location to save the files which are Split from the original file.
            OutputStream outputStream = new FileOutputStream(videoFile);
            System.out.println("File Created Location: "+ videoFile);
            int totalPartsToSplit = 20;// Total files to split.
            int splitSize = inputStream.available() / totalPartsToSplit;
            int streamSize = 0;
            int read = 0;
            while ((read = inputStream.read()) != -1) {

                if (splitSize == streamSize) {
                    if (i != totalPartsToSplit) {
                        i++;
                        String fileCount = String.format("%02d", i); // output will be 1 is 01, 2 is 02
                        videoFile = splitFile.getAbsolutePath() +"/"+ fileCount +"_"+ file.getName();
                        outputStream = new FileOutputStream(videoFile);
                        System.out.println("File Created Location: "+ videoFile);
                        streamSize = 0;
                    }
                }
                outputStream.write(read);
                streamSize++;
            }

            inputStream.close();
            outputStream.close();
            System.out.println("Total files Split ->"+ totalPartsToSplit);
        } else {
            System.err.println(file.getAbsolutePath() +" File Not Found.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

Console Output:

控制台输出:

File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/01_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/02_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/03_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/04_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/05_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/06_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/07_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/08_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/09_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/10_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/11_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/12_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/13_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/14_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/15_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/16_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/17_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/18_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/19_Despicable Me 2 - Trailer (HD) - YouTube.mp4
File Created Location: C:\Documents\Videos_Split\Despicable Me 2 - Trailer (HD) - YouTube/20_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Total files Split ->20

Screenshot of Saved video files in Windows 8:

Windows 8 中保存的视频文件的屏幕截图:

Split video file using java into individual parts

使用 java 将视频文件拆分为单独的部分

Below is the code for Join all video files as a single video file after split the video into multiple video files.

以下是将视频拆分为多个视频文件后,将所有视频文件加入为单个视频文件的代码。

Note:Required jar file commons-io-2.2.jar

注意:需要的jar文件commons-io-2.2.jar

Code:

代码:

package com.uk.mysqlmaven.jsf.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
/**
 * 
 * @author uday.p
 *
 */
public class JoinVideoFile {
    public static void main(String[] args) {
        try {
            File splitFiles = new File("C:/Documents/Videos_Split/Despicable Me 2 - Trailer (HD) - YouTube/");// get all files which are to be join
            if (splitFiles.exists()) {
                File[] files = splitFiles.getAbsoluteFile().listFiles();
                if (files.length != 0) {
                    System.out.println("Total files to be join: "+ files.length);

                String joinFileName = Arrays.asList(files).get(0).getName();
                System.out.println("Join file created with name -> "+ joinFileName);

                String fileName = joinFileName.substring(0, joinFileName.lastIndexOf("."));// video fileName without extension
                File fileJoinPath = new File("C:/Documents/Videos_Join/"+ fileName);// merge video files saved in this location

                if (!fileJoinPath.exists()) {
                    fileJoinPath.mkdirs();
                    System.out.println("Created Directory -> "+ fileJoinPath.getAbsolutePath());
                }

                OutputStream outputStream = new FileOutputStream(fileJoinPath.getAbsolutePath() +"/"+ joinFileName);

                for (File file : files) {
                    System.out.println("Reading the file -> "+ file.getName());
                    InputStream inputStream = new FileInputStream(file);

                    int readByte = 0;
                    while((readByte = inputStream.read()) != -1) {
                        outputStream.write(readByte);
                    }
                    inputStream.close();
                }

                System.out.println("Join file saved at -> "+ fileJoinPath.getAbsolutePath() +"/"+ joinFileName);
                outputStream.close();
            } else {
                System.err.println("No Files exist in path -> "+ splitFiles.getAbsolutePath());
            }
        } else {
            System.err.println("This path doesn't exist -> "+ splitFiles.getAbsolutePath());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}

Console output:

控制台输出:

Total files to be join: 20
Join file created with name -> 01_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 01_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 02_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 03_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 04_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 05_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 06_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 07_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 08_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 09_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 10_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 11_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 12_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 13_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 14_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 15_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 16_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 17_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 18_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 19_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Reading the file -> 20_Despicable Me 2 - Trailer (HD) - YouTube.mp4
Join file saved at -> C:\Documents\Videos_Join_Despicable Me 2 - Trailer (HD) - YouTube/01_Despicable Me 2 - Trailer (HD) - YouTube.mp4

Screenshot of Join Video file saved in Windows 8:Join file screenshot

在 Windows 8 中保存的加入视频文件的屏幕截图:加入文件截图

回答by Naveen Maurya

video splited successfully but video not playing( The Player might not support the file type or might not support the codec that was used to compress the file.)

视频拆分成功但视频无法播放(播放器可能不支持文件类型或可能不支持用于压缩文件的编解码器。)

package Spitvideo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
/**
 * 
 * @author uday.p
 *
 */
public class SplitVideoFile {
    public static void main(String[] args) {
        try {
            File file = new File("f:/SampleVideo_1080x720_30mb.mp4");//File read from Source folder to Split.
            if (file.exists()) {

            String videoFileName = file.getName().substring(0, file.getName().lastIndexOf(".")); // Name of the videoFile without extension
            File splitFile = new File("d:/"+ videoFileName);//Destination folder to save.
            if (!splitFile.exists()) {
                splitFile.mkdirs();
                System.out.println("Directory Created -> "+ splitFile.getAbsolutePath());
            }

            int i = 01;// Files count starts from 1
            InputStream inputStream = new FileInputStream(file);
            String videoFile = splitFile.getAbsolutePath() +"/"+ String.format("%02d", i) +"_"+ file.getName();// Location to save the files which are Split from the original file.
            OutputStream outputStream = new FileOutputStream(videoFile);
            System.out.println("File Created Location: "+ videoFile);
            int totalPartsToSplit = 5;// Total files to split.
            int splitSize = inputStream.available() / totalPartsToSplit;
            int streamSize = 0;
            int read = 0;
            System.err.println("<<<<<<<<"+splitSize);
            while ((read = inputStream.read()) != -1) {

                if (splitSize == streamSize) {
                    if (i != totalPartsToSplit) {
                        i++;
                        String fileCount = String.format("%02d", i); // output will be 1 is 01, 2 is 02
                        videoFile = splitFile.getAbsolutePath() +"/"+ fileCount +"_"+ file.getName();
                        outputStream = new FileOutputStream(videoFile);
                        System.out.println("File Created Location: "+ videoFile);
                        streamSize = 0;
                    }
                }
                outputStream.write(read);
                streamSize++;
            }

            inputStream.close();
            outputStream.close();
            System.out.println("Total files Split ->"+ totalPartsToSplit);
        } else {
            System.err.println(file.getAbsolutePath() +" File Not Found.");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
}