讀取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 }

完!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM