使用Java新特性来解压zip文件

如果用一般的文件流操作来解压zip文件,稍微会有点麻烦。JavaSE7的java.nio.file包新加了几个新类,我们可以利用他们来简化解压过程。

zip文件名用String变量zipFile来表示。

1 定义一个zip文件的文件系统:

1
FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile),  null );

 2 获取当前目录

1
final  String currentPath = System.getProperty( "user.dir" );

 注意,因为稍后在匿名类中会用到变量currentPath,所以需要定义为final

3 利用Files的静态方法walkFileTree遍历整个zip文件系统,同时将文件拷贝到指定目录

 

 3.1 调用getPath来获取zip文件系统的根目录

1
fs.getPath( "/" )

 3.2 new一个SimpleFileVisitor<Path>,便利文件系统时可获取文件的属性。

1
2
new  SimpleFileVisitor<Path>() {
     public  FileVisitResult visitFile(Path file, BasicFileAttributes attrs)  throws  IOException {

 3.3 获取目的地址,其中Paths.get可将两个合法的地址拼接为一个

1
Path destPath = Paths.get(currentPath, file.toString());

 3.4 如果目标文件已经存在,则删除

1
Files.deleteIfExists(destPath);

 3.5 创建文件的父目录,不管是文件isFile还是isDirectory,按照Linux文件系统的观点,都可以用同一种方式来处理,即首先创建父目录,然后创建文件(文件夹)。

1
Files.createDirectories(destPath.getParent());

 3.6 移动文件

1
Files.move(file, destPath);

 

完整代码清单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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;
             }
         });
     }
}

出处:https://www.cnblogs.com/lyndon-chen/p/3575393.html


猜你喜欢

转载自blog.csdn.net/ruoxuan25/article/details/80913259
今日推荐