java 单个文件或多文件压缩解决方案 通常比较容易:均基于流的操作,易于理解。
1、首先单文件压缩工具代码:
/**
* 压缩单个文件
*
* @param filepath 需要压缩文件路径
* @param zippath 压缩到哪
*/
public static void zipFile(String filepath, String zippath) {
ZipOutputStream zipOut = null;
BufferedReader input = null;
FileInputStream bis = null;
BufferedOutputStream bo = null;
try {
File file = new File(filepath);
File zipFile = new File(zippath);
bis = new FileInputStream(file);
input = new BufferedReader(new InputStreamReader(bis,StandardCharsets.UTF_8), 1024 * 518);
zipOut = new ZipOutputStream(new FileOutputStream(zipFile), StandardCharsets.UTF_8);
zipOut.putNextEntry(new ZipEntry(file.getName()));
bo = new BufferedOutputStream(zipOut);
String temp;
while ((temp=input.readLine())!=null) {
bo.write((temp+ "\n").getBytes(StandardCharsets.UTF_8));
}
bo.flush();
log.info("压缩文件完成!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != zipOut && null != bo) {
bis.close();
input.close();
zipOut.close();
bo.close();
}
} catch (IOException ignored) {
}
}
}
2、多文件压缩:原理同上类似,只是传被压缩文件的list
/**
* 批量压缩文件
* @param filePaths 需要压缩的文件地址列表(绝对路径)
* @param zipFilePath 需要压缩到哪个zip文件(无需创建这样一个zip,只需要指定一个全路径)
* @param keepDirStructure 压缩后目录是否保持原目录结构
* @throws IOException
* @return int 压缩成功的文件个数
*/
public static int batchZipFile(List<String> filePaths, String zipFilePath,Boolean keepDirStructure) {
byte[] buf = new byte[1024];
File zipFile = new File(zipFilePath);
//zip文件不存在,则创建文件,用于压缩
/* if(!zipFile.exists())
zipFile.createNewFile();*/
int fileCount = 0;//记录压缩了几个文件?
try {
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
for(String relativePath : filePaths){
File sourceFile = new File(relativePath);//绝对路径找到file
if(sourceFile == null || !sourceFile.exists()){
log.info("此文件为空:{}",relativePath);
continue;
}
FileInputStream fis = new FileInputStream(sourceFile);
if(keepDirStructure!=null && keepDirStructure){
//保持目录结构
zos.putNextEntry(new ZipEntry(relativePath));
}else{
//直接放到压缩包的根目录
zos.putNextEntry(new ZipEntry(sourceFile.getName()));
}
log.info("压缩当前文件:"+relativePath);
int len;
while((len = fis.read(buf)) > 0){
zos.write(buf, 0, len);
}
zos.closeEntry();
fis.close();
fileCount++;
}
zos.close();
log.info("压缩完成");
} catch (Exception e) {
e.printStackTrace();
}
return fileCount;
}
3、测试代码:
main方法可以直接测试,此处省略,大家一定测试一下,此功能不难且实用。博主亲测好使、性能高。