import org.apache.commons.io.IOUtils; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream;
public static void main(String[] args) {
//压缩后的文件存放地址及文件名称 ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("D:\\test.zip")));
try {
//查找resources文件下mapper/knowledge文件夹位置 String patch = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "mapper/knowledge"; System.out.println(patch); File sourceFile = new File(patch); //是否文件 if (sourceFile.isFile()) { toZip(sourceFile, zip, ""); } else { fileToZip(sourceFile, zip, ""); } zip.closeEntry(); } catch ( Exception e) { e.printStackTrace(); } //必须要关闭流 IOUtils.closeQuietly(zip);
}
/** * 压缩文件夹 * * @param file 源文件 * @param zip 压缩文件路径 * @param targetPath 目录位置 * @throws Exception 异常 */
private static void fileToZip(File file, ZipOutputStream zip,String targetPath)throws Exception{ //文件地址 String fileName = file.getName(); targetPath +=fileName+File.separator; //插入目录 ZipEntry entry =new ZipEntry(targetPath); zip.putNextEntry(entry); zip.closeEntry(); if(file.listFiles() == null||file.listFiles().length==0)return; //读取文件夹下面所有目录 File[] fileLists= file.listFiles(); //逐个循环 for (File fileList : fileLists) { //是否是文件夹 if(!fileList.isDirectory()){ //插入文件 toZip(fileList,zip,targetPath); }else { fileToZip(fileList,zip,targetPath); } } } /** * 插入文件 * @param file 文件file * @param zip 输出zip * @param targetPath 目录位置 * @throws Exception 异常 */ private static void toZip(File file, ZipOutputStream zip,String targetPath ) throws Exception { //文件位置 ZipEntry entry = new ZipEntry(targetPath + file.getName()); byte[] buf = new byte[1024]; zip.putNextEntry(entry); //流的方式插入zip InputStream read = new FileInputStream(file); int ch = -1; while ((ch = read.read(buf)) != -1) { zip.write(buf, 0, ch); } read.close(); zip.closeEntry(); }