Reputation: 1375
I am trying to unzip a file from sdcard using below code
public void unzip(String zipFilePath, String destDirectory, String filename) throws IOException {
File destDir = new File(destDirectory);
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
// iterates over entries in the zip file
while (entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
if (!entry.isDirectory()) {
// if the entry is a file, extracts it
extractFile(zipIn, filePath);
} else {
// if the entry is a directory, make the directory ;
File dir = new File(filename);
dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}
/**
* Extracts a zip entry (file entry)
* @param zipIn
* @param filePath
* @throws IOException
*/
private void extractFile(ZipInputStream zipIn, String filePath) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
The above code is giving me errors. below are the logs
java.io.FileNotFoundException: /mnt/sdcard/unZipedFiles/myfile/tt/images.jpg: open failed: ENOENT (No such file or directory)
Here I ziped directory which contains images/sub-directory, then I am trying to unzip.
Can anybody tell me the reasons
Thanks
Upvotes: 1
Views: 182
Reputation: 1006789
You are trying to write files to a directory that does not exist. This will not work. Not only do you need to create the files when unZIPping, you need to create the directories as well.
Add the following to extractPath()
as its opening line:
filePath.getParentFile().mkdirs();
This gets the directory that should contain your desired file (filePath.getParentFile()
), then creates all necessary subdirectories to get there (mkdirs()
).
Upvotes: 1