Java ZipOutputStream压缩文件目录或文件

网上介绍Java使用ZipOutputStream大多数不是期望的方式,很多压缩的时候写的是绝对路径

如:D:/abc/  压缩的时候以同样的文件路径写到ZIP文件上,各式各样的问题反正达不到预期的效果,结合之前所学写出最简洁易理解的Java Zip压缩和打包文件目录的方法


		Path filepath = Paths.get("E:\\siniSVN\\res\\AAMS-V10");//目标文件夹
		String zipname = "D:\\abcd.zip";//目标输出路径
		try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipname))) {
			Files.walkFileTree(filepath, new SimpleFileVisitor() {
				@Override
				public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
					ZipEntry dirEntry = new ZipEntry(this.replaceRootDir(dir) + "/");
					zipOutputStream.putNextEntry(dirEntry);
					zipOutputStream.closeEntry();
					return super.preVisitDirectory(dir, attrs);
				}

				@Override
				public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
					zipFile(file);
					return super.visitFile(file, attrs);
				}

				private Path replaceRootDir(Path dir) {
					Path subpath = dir.subpath(filepath.getParent().getNameCount(), dir.getNameCount());
					return subpath;
				}

				private void zipFile(Path file) throws IOException {
					Path subPath = replaceRootDir(file);
					//文件压缩
					ZipEntry zipEntry = new ZipEntry(subPath.toString());
					zipOutputStream.putNextEntry(zipEntry);
					try (BufferedInputStream fileInputStream = new BufferedInputStream(new FileInputStream(file.toFile()))) {
						byte[] buffer = new byte[1024];
						while (fileInputStream.read(buffer) != -1) {
							zipOutputStream.write(buffer);
						}
						zipOutputStream.closeEntry();
					}
				}
			});
		}
	

你可能感兴趣的:(Java程序,java)