文件的合并:
例:将两个图片进行合并,一张图片大小为19KB,一张图片大小为61KB。
public class TestMerge {
public static void merge(String[] srcFiles, String destFilePath) {
if (srcFiles == null) {
throw new IllegalArgumentException(srcFiles + " must be not null");
}
File destFile = new File(destFilePath);
File parent = destFile.getParentFile();
if (!parent.exists()) {
boolean effect = parent.mkdirs();
if (!effect) {
throw new IllegalArgumentException(parent + " create failed");
}
}
for (String src : srcFiles) {
File srcFile = new File(src);
try (FileInputStream in = new FileInputStream(srcFile);
FileOutputStream out = new FileOutputStream(destFile, true)) {
byte[] buff = new byte[1024];
int len = -1;
while ((len = in.read(buff)) != -1) {
out.write(buff, 0, len);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
String[] srcFiles = {"D:" + File.separator + "TestCode" + File.separator + "iotest" + File.separator + "reflex2.png",
"D:" + File.separator + "TestCode" + File.separator + "iotest" + File.separator + "reflex1.png"};
String destFilePath = "D:" + File.separator + "TestCode" + File.separator + "iotest"+File.separator+"reflex.png";
merge(srcFiles,destFilePath);
}
}
合并后:
拆分:
例:将上述合并后的图片拆分回原来的照片大小,并且能够正常显示。
public class TestSplit {
public static void main(String[] args) throws IOException {
String directory = "D:" + File.separator + "TestCode" + File.separator + "iotest" + File.separator;
File srcFile = new File(directory + "reflex3.png");
File destFile1 = new File(directory + "picture1.png");
File destFile2 = new File(directory + "picture2.png");
long len = srcFile.length();
//这里的字节数要看文件实际占用空间大小,windows对于KB的处理会采用四舍五入
long size1 = 19268;
long size2 = 62110;
//设置文件指针偏移,从该文件的开头测量,发生下一次读取或写入。即第二个文件写入的开始点
long pos = size1;
//将源文件写入内存
RandomAccessFile rf = new RandomAccessFile(srcFile, "rw");
//创建导出文件
File[] files = new File[2];
files = new File[]{destFile1, destFile2};
//循环读取文件内容
for (int i = 0; i <= 1; i++) {
//缓冲输出流,创建一个新的缓冲输出流,以将数据写入指定的底层输出流。
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(files[i]));
byte[] bs;
//第一个文件读取的字节大小
if (i == 0) {
bs = new byte[(int) size1];
rf.read(bs);
} else {
//第二个文件读取的字节大小
rf.seek(pos);
bs = new byte[(int) size2];
rf.read(bs);
}
out.write(bs);
out.flush();
out.close();
}
}
}
拆分结果: