Read the parts of the bytes into a byte array and save them in new files when the buffer is full or is the end of the file.
For example (the code is not perfect, but it should help to understand the process)
class FileSplit { public static void splitFile(File f) throws IOException { int partCounter = 1;
myFile.mp4 size = 12.7 MB
After the split, I had 13 files
myFile.mp4.001 - myFile.mp4.012 with a size of 1 MBmyFile.mp4.013 with a size of 806 KB
If you want to combine these files, you can use
public static void mergeFiles(List<File> files, File into) throws IOException { try (FileOutputStream fos = new FileOutputStream(into); BufferedOutputStream mergingStream = new BufferedOutputStream(fos)) { for (File f : files) { Files.copy(f.toPath(), mergingStream); } } }
You can also create some additional ways to make your life easier. For example, a method that will create a list of files containing individual parts based on the name (and location) of one of these files.
public static List<File> listOfFilesToMerge(File oneOfFiles) { String tmpName = oneOfFiles.getName();//{name}.{number} String destFileName = tmpName.substring(0, tmpName.lastIndexOf('.'));//remove .{number} File[] files = oneOfFiles.getParentFile().listFiles( (File dir, String name) -> name.matches(destFileName + "[.]\\d+")); Arrays.sort(files);//ensuring order 001, 002, ..., 010, ... return Arrays.asList(files); }
Using this method, we can overload the mergeFiles method to use only one of the File oneOfFiles files instead of the entire List<File> list (we will create this list based on one of the files)
public static void mergeFiles(File oneOfFiles, File into) throws IOException { mergeFiles(listOfFilesToMerge(oneOfFiles), into); }
You can also overload these methods to use String instead of File (if necessary, we will wrap each line in the file)
public static List<File> listOfFilesToMerge(String oneOfFiles) { return listOfFilesToMerge(new File(oneOfFiles)); } public static void mergeFiles(String oneOfFiles, String into) throws IOException{ mergeFiles(new File(oneOfFiles), new File(into)); }