I’m extracting a file from a zip archive using this code (omitting all the catch statements and other initialization statements):
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;
}
}
This code works fine when extracting a file in say, /archive.zip/file_i_need.txt.
But when I’m trying to extract a file from /archive.zip/folder1/file_i_need.txt, I get an exception java.lang.NullPointerException when I try to use readLine() to read the file in:
String line = null ;
BufferedReader input = new BufferedReader(newFileReader(extractedFile)) ;
while( (line = input.readLine() ) != null ) {
...
}
I’ve tested it on both cases and it seems like this code will not work when the file is inside a folder because the extractedFileName is ‘folder/file_i_need.txt’ compared to just ‘file_i_need.txt’.
Any suggestions you can recommend?
Thanks!
The problem is you’re not taking into account that the entries name may contain a path element, which you are not creating, you simply try an write to the file. Why this doesn’t produce an error, I’m not sure.
Are you writing these files on Windows?? This would create a file like
folder1/file_i_need.txton the file system, which is probably invalid at some level 😛Try extracting the file name from the
ZipEntryObviously, check that name actually contains a “/” first 😉
UPDATE
While I’m at it, this looks wrong
Basically your saying
outputDir + outerZipEntry.getName() + (outputDir + outerZipEntry.getName())UPDATE
I tested this on Windows and I get a
FileNotFoundExceptionwhen I try and write the file to a path that does not existI also tested it on my MaC and I get a
FileNotFoundExceptionI don’t know what your error handling is doing, but it’s doing it wrong.