小编典典
当缓冲区已满或文件结束时,将字节的一部分读取到字节数组中并将其存储在新文件中。
例如(代码不是完美的,但是它应该有助于理解过程)
class FileSplit {
public static void splitFile(File f) throws IOException {
int partCounter = 1;//I like to name parts from 001, 002, 003, ...
//you can change it to 0 if you want 000, 001, ...
int sizeOfFiles = 1024 * 1024;// 1MB
byte[] buffer = new byte[sizeOfFiles];
String fileName = f.getName();
//try-with-resources to ensure closing stream
try (FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis)) {
int bytesAmount = 0;
while ((bytesAmount = bis.read(buffer)) > 0) {
//write each chunk of data into separate file with different number in name
String filePartName = String.format("%s.%03d", fileName, partCounter++);
File newFile = new File(f.getParent(), filePartName);
try (FileOutputStream out = new FileOutputStream(newFile)) {
out.write(buffer, 0, bytesAmount);
}
}
}
}
public static void main(String[] args) throws IOException {
splitFile(new File("D:\\destination\\myFile.mp4"));
}
}
myFile.mp4大小= 12.7 MB
拆分后我有13个文件
myFile.mp4.001- myFile.mp4.012大小为1 MB
myFile.mp4.013 大小806 KB
如果要合并这些文件,可以使用
public static void mergeFiles(List 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);
}
}
}
您还可以创建一些其他方法来简化生活。例如,实例方法将基于这些文件之一的名称(和位置)创建包含分开的零件的文件列表。
public static List 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);
}
使用该方法,我们可以重载mergeFiles方法以仅使用一个文件File
oneOfFiles而不是整个列表List(我们将基于其中一个文件生成该列表)
public static void mergeFiles(File oneOfFiles, File into)
throws IOException {
mergeFiles(listOfFilesToMerge(oneOfFiles), into);
}
您也可以重载这些方法以String代替使用File(我们将在需要时将每个String包裹在File中)
public static List 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));
}
2020-10-07