Java 合并多个碎片文件到一个文件,也可以直接使用linux cat命名
linux cat命令
cat *.zip.* > out.zip
java工具使用方式
# 编译
javac CombineFile.java
# 执行
java CombineFile D:/data/out.zip D:/data/test.zip.01 D:/data/test.zip.02
USAGE: CombineFile outFile inFiles...
outFile 输出文件名
inFiles 输入文件名,支持多个
如: java CombineFile D:/data/file D:/data/dir/
如: java CombineFile D:/data/file D:/data/dir1/ D:/data/dir2/file1
源代码 CombineFile.java
// package me.muphy.file;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
public class CombineFile {
public static void main(String[] args) throws IOException {
if (args.length < 2) {
System.out.println("USAGE: CombineFile outFile inFiles...");
System.out.println("\toutFile 输出文件名");
System.out.println("\tinFiles 输入文件名,支持多个");
System.out.println("\t如: CombineFile D:/data/file D:/data/dir/");
System.out.println("\t如: CombineFile D:/data/file D:/data/dir1/ D:/data/dir2/file1");
return;
}
// 1.获取所有的输入文件
String outFileName = args[0];
List<File> inFiles = new ArrayList<>();
for (int i = 1; i < args.length; i++) {
File file = new File(args[i]);
if (!file.exists()) {
System.out.println(args[i] + " 文件或者目录不存在!");
return;
}
if (file.isFile()) {
inFiles.add(file);
} else if (file.isDirectory()) {
File[] files = file.listFiles();
if (files == null || files.length < 1) {
System.out.println(args[i] + " 目录不存在任何文件!");
return;
}
inFiles.addAll(Arrays.asList(files));
}
}
if (inFiles.isEmpty()) {
System.out.println("目录不存在任何文件!");
return;
}
inFiles.sort(Comparator.comparing(File::getName));
// 2.复制文件内容
File fo = new File(outFileName);
FileOutputStream fos = new FileOutputStream(fo);
FileInputStream fis = null;
try {
for (File file : inFiles) {
fis = new FileInputStream(file);
byte[] buf = new byte[1024];
int length;
while ((length = fis.read(buf)) > 0) {
fos.write(buf, 0, length);
}
fis.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
if (fis != null) {
try {
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
标签:文件,java,inFiles,file,linux,Java,data,CombineFile,out
From: https://www.cnblogs.com/muphy/p/17183518.html