如果用一般的文件流操作来解压zip文件,稍微会有点麻烦。JavaSE7的java.nio.file包新加了几个新类,我们可以利用他们来简化解压过程。
zip文件名用String变量zipFile来表示。
1 定义一个zip文件的文件系统:
FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), null);
2 获取当前目录
final String currentPath = System.getProperty("user.dir");
注意,因为稍后在匿名类中会用到变量currentPath,所以需要定义为final
3 利用Files的静态方法walkFileTree遍历整个zip文件系统,同时将文件拷贝到指定目录
3.1 调用getPath来获取zip文件系统的根目录
fs.getPath("/")
3.2 new一个SimpleFileVisitor<Path>,便利文件系统时可获取文件的属性。
new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
3.3 获取目的地址,其中Paths.get可将两个合法的地址拼接为一个
Path destPath = Paths.get(currentPath, file.toString());
3.4 如果目标文件已经存在,则删除
Files.deleteIfExists(destPath);
3.5 创建文件的父目录,不管是文件isFile还是isDirectory,按照Linux文件系统的观点,都可以用同一种方式来处理,即首先创建父目录,然后创建文件(文件夹)。
Files.createDirectories(destPath.getParent());
3.6 移动文件
Files.move(file, destPath);
完整代码清单
import java.io.IOException; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; public class Zipper { public static void main(String[] args) throws Exception { if (args.length == 0) { System.out.println("Usage: java Zipper zipfilename"); System.exit(0); } unzip(args[0]); } public static void unzip(String zipFile) throws Exception { FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), null); final String currentPath = System.getProperty("user.dir"); System.out.println("current directory:" + currentPath); Files.walkFileTree(fs.getPath("/"), new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path destPath = Paths.get(currentPath, file.toString()); Files.deleteIfExists(destPath); Files.createDirectories(destPath.getParent()); Files.move(file, destPath); return FileVisitResult.CONTINUE; } }); } }