使用Java实现对文件的切片和合并
切片
private static void cutFile() throws Exception {
long startTime = System.currentTimeMillis();
FileInputStream fis = null;
FileOutputStream fos = null;
int i = 1;
int length = 0;
byte[] data = new byte[1024 * 1024]; //1024 * 1024 = 1MB
File file = new File("C:\\Users\\wjq\\Desktop\\test\\testCut.rar");
try {
fis = new FileInputStream(file);
while ((length = fis.read(data)) != -1) {
fos = new FileOutputStream("C:\\Users\\wjq\\Desktop\\test\\" + i + ".rar");
fos.write(data, 0, length);
logger.info("正在切分第" + i + "个文件,文件大小:" + fos.getChannel().size() / 1024 + "KB");
fos.close();
i++;
}
fis.close();
long endTime = System.currentTimeMillis();
logger.info("文件切分已完成,共耗时:" + (endTime - startTime) + "ms");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (!StringUtil.isEmpty(fis)) {
fis.close();
}
if (!StringUtil.isEmpty(fos)) {
fos.close();
}
}
}
合并
private static void conFile() throws Exception {
long startTime = System.currentTimeMillis();
byte[] data = new byte[1024 * 1024]; //一次读取 1024 * 1024 = 1MB
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
File file = new File("C:\\Users\\wjq\\Desktop\\test\\");
String[] listFiles = file.list();
bos = new BufferedOutputStream(new FileOutputStream("C:\\Users\\wjq\\Desktop\\testCon.rar"));
for (int i = 1; i <= listFiles.length; i++) {
bis = new BufferedInputStream(new FileInputStream(new File("C:\\Users\\wjq\\Desktop\\test\\" + i + ".rar")));
while (bis.read(data) != -1) {
bos.write(data);
}
bis.close();
logger.info("已完成第" + i + "块文件的合并,文件大小:" + data.length / 1024 + "KB");
}
bos.close();
long endTime = System.currentTimeMillis();
logger.info("文件合并已完成,文件大小 ==> {}, 共耗时 ==> {}", new FileInputStream("C:\\Users\\wjq\\Desktop\\testCon.rar").getChannel().size() / 1024 + "KB", (endTime - startTime) + "ms");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (!StringUtil.isEmpty(bis)) {
bis.close();
}
if (!StringUtil.isEmpty(bos)) {
bos.close();
}
}
}