ZipEntry getEntry()总是返回null
问题描述:
我有一个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文件有很多子目录,我需要通过搜索来查找截图吗?
答
我能够使用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
类来解决这个问题。
您必须提供完整路径,而不仅仅是名称,路径必须与文件中的内容完全一致。 – EJP