0

我正在使用此代码从 zip 存档中提取文件(省略所有 catch 语句和其他初始化语句):

zipInputStream = new ZipInputStream(new FileInputStream(file));
zipFile = new ZipFile(file);
for (Enumeration<?> em = zipFile.entries(); em.hasMoreElements();) {
    String extractedFileName = em.nextElement().toString();
    ZipEntry outerZipEntry = zipInputStream.getNextEntry();
    if (outerZipEntry.getName().contains(searchString)) {
        extractedFile = new File(outputDir + outerZipEntry.getName());
        out = new FileOutputStream(outputDir + extractedFileName);
        byte[] buf = new byte[1024];
        int len;
        while ((len = zipInputStream.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        break;
     } 
}

提取文件时,此代码可以正常工作,例如 /archive.zip/file_i_need.txt。

但是,当我尝试从 /archive.zip/folder1/file_i_need.txt 中提取文件时,当我尝试使用 readLine() 读取文件时出现异常 java.lang.NullPointerException:

String line = null ;
BufferedReader input = new BufferedReader(newFileReader(extractedFile)) ;
while( (line = input.readLine() ) != null ) {
    ...
}

我在这两种情况下都对其进行了测试,当文件位于文件夹中时,此代码似乎不起作用,因为提取的文件名是 'folder/file_i_need.txt' 而只是 'file_i_need.txt'。

你有什么建议可以推荐吗?

谢谢!

4

3 回答 3

1

我认为您的问题是您无法在线打开 FileOutputStream out = new FileOutputStream(outputDir + extractedFileName);。您无法打开流,因为例如 if和 outputDirextractedFileNamefolder1/file_i_need.txtC:/OutputDir那么您正试图在C:/OutputDirfolder1/file_i_need.txt. 这样的目录不存在并且 out 变为空。我在评论中提到的帖子确实具有解压缩操作,然后您可以看到对 zip 文件中目录条目的特殊处理。

于 2012-08-13T20:14:01.787 回答
1
extractedFile = new File(outputDir + outerZipEntry.getName());

问题是您没有考虑到条目名称可能包含您没有创建的路径元素,您只需尝试写入文件即可。为什么这不会产生错误,我不确定。

你是在 Windows 上写这些文件吗?这将folder1/file_i_need.txt在文件系统上创建一个文件,这可能在某种程度上是无效的:P

尝试从ZipEntry

String name = outerZipEntry.getName();
name = name.substring(name.lastIndexOf("/") + 1);

显然,首先检查名称实际上是否包含“/”;)

更新

当我在做的时候,这看起来不对

extractedFile = new File(outputDir + outerZipEntry.getName());
out = new FileOutputStream(outputDir + extractedFileName);

基本上你的说法outputDir + outerZipEntry.getName() + (outputDir + outerZipEntry.getName())

更新

我在 Windows 上对此进行了测试,FileNotFoundException当我尝试将文件写入不存在的路径时,我得到了

我还在我的 Mac 上对其进行了测试,我得到了一个FileNotFoundException

我不知道您的错误处理在做什么,但它做错了。

于 2012-08-13T20:19:31.883 回答
0

您正在以两种不同的方式迭代 zip 条目:

迭代 1:

for (Enumeration<?> em = zipFile.entries(); em.hasMoreElements();) {

迭代 2:

ZipEntry outerZipEntry = zipInputStream.getNextEntry();

只做其中之一。使用ZipFileAPI 或ZipInputStreamAPI。我强烈怀疑这就是它的NullPointerException来源。

于 2012-08-13T19:28:50.443 回答