2017-08-03 175 views
0

我有一個zip文件,我想從中提取文件,現在我有這個代碼應該通過Spring控制器發送該文件。ZipEntry getEntry()總是返回null

//This code is in a Spring Controller to send the screenshot. 
    ZipFile file = new ZipFile("path/to/zipFile.zip"); 
    try(InputStream is = searchImage(screenshotFileName, file)){ 
     response.setHeader("Cache-Control", "no-store"); 
     response.setHeader("Pragma", "no-cache"); 
     response.setDateHeader("Expires", 0); 
     response.setContentType("image/png"); 
     ServletOutputStream servletOutputStream = response.getOutputStream(); 
     IOUtils.copy(is,servletOutputStream); 
    }catch (IOException e){ 
     response.sendError(HttpServletResponse.SC_NOT_FOUND); 
    } 


private InputStream searchImage(String screenshotFileName, ZipFile file) throws IOException{ 
    ZipEntry entry = file.getEntry(screenshotFileName); 
    if(entry != null){ 
     return file.getInputStream(entry); 
    } 
    return null; 
} 

是我遇到的問題是,每到這個代碼運行時,InputStream正在返回null意味着該getEntry方法沒有找到截圖。我查看了zip文件,並知道屏幕截圖文件存在於壓縮文件中。我是否在談論這個錯誤?我正在查找的zip文件有很多子目錄,我需要通過搜索來查找截圖嗎?

+0

您必須提供完整路徑,而不僅僅是名稱,路徑必須與文件中的內容完全一致。 – EJP

回答

0

我能夠使用FileSystem以不同的方式從zip文件中提取單個文件。您可以通過使用此代碼

File outputFile = new File("C:\\" + screenshotFileName); 
Path zipFile = Paths.get("\\path\\to\\Zip.zip"); 
FileSystem fileSystem = FileSystems.newFileSystem(zipFile,null); 
Path source = fileSystem.getPath(screenshotPath); 
Files.copy(source, outputFile.toPath()); 

現在可以輕鬆地創建輸入流,因爲從zip中的文件不位於C:\screenshotFileName提取單個文件。無需使用ZipEntry類來解決這個問題。