public class ZipTest { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub File source = new File("D:\\Java\\demo"); File target = new File("D:\\Java\\demo.zip"); toZip(source, target); Desktop.getDesktop().open(target); } public static void toZip(File source, File target) throws IOException { try (ZipOutputStream outPut = new ZipOutputStream(new FileOutputStream(target))) { File[] files = source.listFiles(); for (File file : files) { zipTools(file, source, outPut); outPut.closeEntry(); } System.out.println(target + "打包结束!"); } } // 递归函数 public static void zipTools(File file, File source, ZipOutputStream outPut) throws IOException { if (file.isFile()) { outPut.putNextEntry(new ZipEntry(getRelativePath(file, source))); outPut.write(Files.readAllBytes(file.toPath())); } else { outPut.putNextEntry(new ZipEntry(getRelativePath(file, source) + File.separator)); for (File subFile : file.listFiles()) { file = subFile; zipTools(subFile, source, outPut); } } } //获得相对路径 public static String getRelativePath(File childFile, File parentFile) { return childFile.getPath().substring(parentFile.getPath().length() + 1); } }
Sign in to make a reply
Best of Me