package webTest;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
public class ZipFileUtils {
public ZipFileUtils(){
}
/**
* 将源文件或者文件夹生成的指定格式的压缩文件,格式rar
* @author xzr
* @version
* @date 创建时间2018年7月3日上午10:37:15
* @param resourcePath 源文件路径
* @param targetPath 处理后的文件路径
* @throws Exception
*/
//这种日志打印使用的是log4j2.xml文件,导入import org.apache.logging.log4j.LogManager和org.apache.logging.log4j.Logger包
private static final Logger logger = LogManager.getLogger(ZipFileUtils.class);
//这种日志打印使用的是log4j.properties文件,导入org.apache.log4j.Logger包
//private static final Logger logger = Logger.getLogger(ZipFileUtils.class);
@SuppressWarnings("resource")
public void zipFile(String resourcePath,String targetPath){
//源文件路径
File resourceFile = new File(resourcePath);
//处理后的文件路径
File targetFile = new File(targetPath);
if(!targetFile.exists()){
logger.info("压缩文件生成路径不存在,创建文件");
targetFile.mkdirs();
}
String resourceName = resourceFile.getName();
String targetName= "";
if(resourceFile.isDirectory()){
//压缩后的文件名rar,可以改成zip
targetName = resourceName+".rar";
}else{
//压缩后的文件名rar,可以改成zip
targetName = resourceName.substring(0,resourceName.indexOf("."))+".rar";
}
try {
FileOutputStream fos = new FileOutputStream(targetPath+"\\"+targetName);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
//resourceFile 源文件 resourceName压缩完的压缩文件里面的文件的名称
createZipFile(zos, resourceFile, resourceName);
//关闭流
zos.close();
fos.close();
logger.info("压缩成功");
} catch (Exception e) {
logger.error("检查文件是否存在,路径是否正确");
}
}
/**
* 生成压缩文件
* @author xzr
* @version
* @date 创建时间2018年7月3日上午10:43:52
* @param zos ZipOutputStream流
* @param file 源文件
* @param dir 压缩完的压缩文件里面的文件的名称
* @throws Exception
*/
public void createZipFile(ZipOutputStream zos ,File file,String dir) {
try {
//如果当前是文件夹进行处理
if(file.isDirectory()){
File[] fileList = file.listFiles();
zos.putNextEntry(new ZipEntry(dir+"/"));
dir = dir.length()==0?"":dir+"/";
//循环将文件夹中文件打包
for (int i = 0; i < fileList.length; i++) {
createZipFile(zos, fileList[i], dir+fileList[i].getName());
}
}else{
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
zos.putNextEntry(new ZipEntry(dir));
//写数据
int j = 0;
byte[] b = new byte[1024];
while((j=bis.read(b))>0){
zos.write(b);
}
bis.close();
fis.close();
}
} catch (Exception e) {
logger.error("文件或读写错误");
e.printStackTrace();
}
}
/**
* 测试主函数
* @author xzr
* @version
* @date 创建时间2018年7月3日上午10:43:30
* @param args
*/
public static void main(String[] args) {
String resourcePath = "d:\\xzr";
String targetPath = "d:\\";
ZipFileUtils zipFileUtils = new ZipFileUtils();
zipFileUtils.zipFile(resourcePath, targetPath);
}
}
文件压缩
最新推荐文章于 2024-05-06 08:55:28 发布