java zip打包多级文件夹目录结构(windows)
大概思路:创建总体输出流zipoutputstream,每次找到文件和文件夹都写入一个zipEntity实例,当为文件夹时,则递归方法继续去找里面的文件,当为文件时则处理文件,且是结束递归的条件
/** * 创建zip文件 * * @param source 被打包的文件目录 * @param zipName 打包后存放的目录及文件名 * @throws FileNotFoundException */ private void createzipFile(String source, String zipName) { File file = new File(source); String zipPath="zip文件存放目录"; try { File file1file1 = new File(zipPath); if (!file1file1.exists()) { file1file1.mkdirs(); } FileOutputStream target = new FileOutputStream(zipName); ZipOutputStream out = new ZipOutputStream(target); getZipFile(out, file, ""); out.close(); } catch (IOException e) { logger.error(e.getMessage()); throw new RuntimeException("创建zip文件失败", e); } } /** * 将对应文件夹下的文件及文件夹写入对应文件夹目录下 * * @param out * @param file * @param pareFileName */ private void getZipFile(ZipOutputStream out, File file, String pareFileName) { try { File files[] = file.listFiles(); for (File dirFile : files) { String temPath = pareFileName; if (dirFile.isDirectory()) { pareFileName += dirFile.getName() + File.separator; ZipEntry zipEntry = new ZipEntry(pareFileName); out.putNextEntry(zipEntry); getZipFile(out, dirFile, pareFileName); } else { pareFileName += dirFile.getName(); FileInputStream fi = new FileInputStream(dirFile); BufferedInputStream origin = new BufferedInputStream(fi); ZipEntry entry = new ZipEntry(pareFileName); out.putNextEntry(entry); int count; while ((count = origin.read()) != -1) { out.write(count); } origin.close(); } pareFileName = temPath; } } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage()); throw new RuntimeException("压缩文件异常", e); } }