学习IO流之处理文件文件
需求:
- 对文件实现分割以及合并
- 实现分割:
- 通过输入流
FileInputStream
读取到文件 - 指定文件大小读取
- 将指定大小文件通过输出流
FileOutputStream
存储
- 实现合并:
- 通过读取原文件夹将读取到的文件进行存储
- 对文件列表进行排序
- 迭代进行写入操作实现合并
详细看代码注释
代码实现 :
import java.io.*;
import java.util.Arrays;
public class FileCutter {
public int split(String str) {
File file = new File(str);
if (!file.exists()) {
throw new RuntimeException(str + ":路径无效!");
}
long size = 1024 * 1024 * 6;
int i = str.lastIndexOf('.');
String targetPath = str.substring(0, i);
File directory = new File(targetPath);
if (!directory.exists()) {
directory.mkdir();
}
int splitCount = split(file, size, directory);
System.out.println("文件分割成了" + splitCount + "个");
return splitCount;
}
public int split(final File original, final long size, final File directory) {
int fileCount = 0;
try (FileInputStream fis = new FileInputStream(original)) {
int flag;
byte[] bytes = new byte[(int) size];
while ((flag = fis.read(bytes)) != -1) {
File file = new File(directory, fileCount + ".FILE");
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(bytes, 0, flag);
}
fileCount++;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return fileCount;
}
public long mergeFile(final File dir, final File target) {
if (!dir.exists() || !target.exists()) {
throw new RuntimeException(dir.exists() || target.exists() ? (dir + "路径不合法") : (target + "路径不合法"));
}
File[] files = dir.listFiles((file, name) -> name.endsWith(".FILE"));
Arrays.sort(files, (a, b) -> {
int num1 = Integer.parseInt(a.getName().replace(".FILE", ""));
int num2 = Integer.parseInt(b.getName().replace(".FILE", ""));
return Integer.compare(num1, num2);
});
File targetFile = new File(target, "merge.mp4");
try (FileOutputStream fos = new FileOutputStream(targetFile)) {
for (File file : files) {
try (FileInputStream fis = new FileInputStream(file)) {
fis.transferTo(fos);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
return targetFile.length();
}
}