读取zip包内根目录文件的文件名

背景:上传压缩包文件,文件上传成功后,验证zip包内是否存在index.html文件 

编码事项:

 1 import java.util.zip.ZipEntry;  //此类用于表示 ZIP 文件条目。
 2 import java.util.zip.ZipInputStream; //此类为读取 ZIP 文件格式的文件实现输入流过滤器。包括对已压缩和未压缩条目的支持。
 3 
 4 public class FileUtil {
 5 
 6   String rootPath = "D:/FILEDOWNLOAD/FTPSERVICE";
 7 
 8   /**
 9   * 读取zip包内根目录文件的文件名
10   * @param path
11   * @return
12   * @throws Exception
13   */
14   public static String readZipFile(String path) throws Exception {
15     String resStr = "";
16     ZipEntry zipEntry = null;
17     File file = new File(rootPath + path); 
18     if (!file.exists()) { //判断文件是否存在,若不存在则从ftp服务器上下载
19       FtpUtil ftp = new FtpUtil();
20       ftp.connectServer();
21       ftp.downloadFile(path, file.getPath());
22       ftp.closeServer();
23     }
24     file = new File(file.getPath());
25     if(file.exists()){
26       ZipInputStream zipInputStream = new ZipInputStream( new FileInputStream(rootPath + path), Charset.forName("GBK")); //解决包内文件存在中文时的中文乱码问题
27       //只读取包内根目录文件的文件名
28       if((zipEntry = zipInputStream.getNextEntry()) != null) {
29         if(zipEntry.isDirectory()){ //遇到文件夹就跳过
30   
31         }else{
32           resStr+=";"+zipEntry.getName();
33           System.out.println(zipEntry.getName());//通过getName()可以得到文件名称
34         }
35       }
36 
37       //读取包内所有文件的文件名
38       /*while ((zipEntry = zipInputStream.getNextEntry()) != null) {
39         if(zipEntry.isDirectory()){ //遇到文件夹就跳过
40           continue;
41         }else{
42           str+=";"+zipEntry.getName().substring(zipEntry.getName().lastIndexOf("/")+1);
43           System.out.println(zipEntry.getName().substring(zipEntry.getName().lastIndexOf("/")+1));//通过getName()可以得到文件名称
44         }
45       }*/
46     }
47     return resStr;
48   }
49 
50 }
51 
52 
53 
54 @RequestMapping("/form")
55 @Controller
56 public class formController extends BaseController {
57 
58   @Log("验证form版本压缩文件根目录是否存在index.html")
59   @ResponseBody()
60   @PostMapping("/validateFormIndexExist")
61   R validateFormIndexExist(String path, String str) {
62     String resStr = "";
63     try {
64       resStr = FileUtil.readZipFile(path);
65       if (StringUtils.isNotBlank(resStr) && resStr.indexOf("index.html")>0) {
66         return R.ok();
67       }
68     } catch (Exception e) {
69       return R.error(e.getMessage());
70     }
71     return R.error(1, "上传版本文件不包含index.html文件,请检查后重新上传!");
72   }
73 
74 }

完!

posted @ 2019-11-29 14:52  壹玖玖肆  阅读(2718)  评论(0编辑  收藏  举报