58,454
社区成员
发帖
与我相关
我的任务
分享
/**
* 文件分割,将大文件分割为多个小文件
* @file 要分割的文件
* @partSize 分割的尺寸,分割后每个小文件的大小,单位:字节
* @return void 分割后的文件存放在和原文件同一个文件夹中,文件名:原文件名.part + 数字
* @throws IOException
*/
public static void split(File file, int partSize) {
FileInputStream fis;
try {
fis = new FileInputStream(file);
byte[] buff = new byte[1024*20];
int buffCount = partSize / (1024*20);
int count = 0;
int i = 1;
File newfile = null;
logger.info("开始分割文件:" + file.getName());
logger.info("分割后的单个文件大小为:" + partSize/1024.0 + "KB");
while(fis.read(buff, 0, buff.length) != -1) {
if(count == 0) {
newfile = new File(file.getParent() + "/" + file.getName() + ".part" + i);
}
if(count < buffCount) {
writeToFileTail(buff, newfile);
count++;
} else {
logger.info("生成文件:" + newfile.getName());
i++;
count = 0;
}
}
fis.close();
logger.info("分割完成,生成分割文件数:" + (i-1));
} catch (FileNotFoundException e) {
logger.error(file.getAbsolutePath() + "文件不存在");
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 合并文件,将多个小文合并为一个大文件
* @param files 要合并的文件,合并顺序为数组的下标顺序,注意要合并的文件的顺序
* @param outFileName 合并后的文件,需要给文件全路径
*/
public static void union(File[] files, String outFileName) {
File outFile = new File(outFileName);
for(int i=0; i<files.length; i++) {
logger.info("合并文件:" + files[i].getAbsolutePath());
appendFile(files[i], outFile);
}
logger.info("合并完成");
}
/**
* 将byte[]数组内容追加到文件的末尾
* @param content
* @param file
* @return
*/
public static boolean writeToFileTail(byte[] content, File file) {
boolean result = true;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(file, "rw");
raf.seek(raf.length()); //指向文件末尾
logger.debug("当前文件指针:" + raf.getFilePointer());
raf.write(content, 0, content.length);
} catch(FileNotFoundException e) {
logger.error(file.getParentFile().getAbsoluteFile() + "目录不存在 ");
return false;
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
close(raf);
}
return result;
}
/**
* 将fromFile文件中的内容追加到toFile文件的末尾
* @param fromFile
* @param toFile
* @return
*/
public static boolean appendFile(File fromFile, File toFile) {
try {
InputStream in = new FileInputStream(fromFile);
return writeToFileTail(in, toFile);
} catch (FileNotFoundException e) {
logger.error(fromFile.getAbsoluteFile() + "文件不存在");
return false;
}
}