I am building a library for android, and it requires me to unzip files. It works on every single other file except for one file in one particular archive. I get a file not found exception on this. I am not a java expert, or an android expert, but my team is also stumped. Just hoping someone can spot something in my code that could be creating a bug.
public static void unzip(File zipFile,
String unzipFilePath,
FetchInterface responseHandler,
JSONObject json) {
final int BUFFER_SIZE = 4096;
String filename;
InputStream inputStream;
ZipInputStream zipInputStream;
ZipEntry zipEntry = null;
String path = unzipFilePath + File.separator;
try {
File dir = new File(path);
if (!dir.exists()) {
dir.mkdirs();
}
String zipRootDirectory = null;
inputStream = new FileInputStream(zipFile);
zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
byte[] buffer = new byte[BUFFER_SIZE];
int count;
// Log.d(tag, zipFile.getName());
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
filename = zipEntry.getName();
Log.d(tag, "ZIP ENTRY: " + zipEntry.getName());
if (zipRootDirectory == null) {
zipRootDirectory = zipEntry.getName().split("\\/")[0];
// Log.d(tag, "ROOT DIR: " + zipRootDirectory);
}
if (zipEntry.isDirectory()) {
Log.d(tag, "ZIPENTRY IS DIR: " + zipEntry.toString());
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
try {
FileOutputStream fout = new FileOutputStream(path + filename);
Log.e(tag, "FILENAME: " + filename);
while ((count = zipInputStream.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
} catch(FileNotFoundException e) {
Log.e(tag, "ERROR AT THIS FILE: " + filename);
e.printStackTrace();
}
zipInputStream.closeEntry();
}
zipInputStream.close();
File zipRootDirectoryFile = new File(path + File.separator + zipRootDirectory);
if (zipRootDirectoryFile.exists()) {
Log.d(tag, zipRootDirectoryFile.getName());
File renameFile = new File(path + File.separator + "html" + File.separator);
zipRootDirectoryFile.renameTo(renameFile);
} else {
Log.e(tag, "directory cannot be renamed as it does not exist");
}
} catch (IOException e) {
e.getStackTrace();
}
}
Related
i've been trying to understand how the multipartfile works in spring
but did't find out any helpful info on internet.
Trying to understand this method:
public String copyUploadedImage(MultipartFile multipartFile, String realpath, int userId) throws IOException {
String orgFileName = null;
orgFileName = multipartFile.getOriginalFilename();
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (multipartFile.getSize() > 0) {
inputStream = multipartFile.getInputStream();
String root = realpath + File.separator + userId + File.separator + "Image" + File.separator;
File file = new File(root + File.separator);
if (file.mkdirs()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
fileName = file + File.separator + multipartFile.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
return orgFileName;
}
below is my method for unzipping folder to destination folder and method definition
unzip(filepath, unzipLocation);
here is my method to unzip a zip file this method works file but getting problem when my zip file comes like a.zip which have folder 2 folder (i.e abc1,abc2) and again folder abc1 have folder and it have files please help me
private void unzip(String src, String dest) {
String _location = "";
final int BUFFER_SIZE = 4096;
_location = dest;
System.out.println("_location ::: " + dest + "");
System.out.println("src ::: " + src + "");
BufferedOutputStream bufferedOutputStream = null;
FileInputStream fileInputStream;
try {
fileInputStream = new FileInputStream(src);
ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(fileInputStream));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String zipEntryName = zipEntry.getName();
String name = dest.substring(dest.lastIndexOf("/") - 1);
// System.out.println("NAME "+name);
// File FileName = new File(FolderName);
File FileName = new File(_location.toString());
if (!FileName.isDirectory()) {
try {
if (FileName.mkdir()) {
} else {
}
} catch (Exception e) {
e.printStackTrace();
}
}
String loc = "";
String fname = "";
String LOC = "";
LOC = _location.toString();
// File file = new File(FolderName+"/" +zipEntryName);
System.out.println("ZIP " + zipEntryName + "");
// zipEntryName=zipEntryName.r
if (zipEntryName.contains("/")) {
String[] file = zipEntryName.split("/");
System.out.println("CHECK ::: " + file.length);
System.out.println("CHECK ::: " + file[0] + "");
String test = zipEntryName.substring(zipEntryName.lastIndexOf("/"), zipEntryName.length());
System.out.println("TEST " + test + "");
if (test.length() > 1) {
LOC = "";
// zipEntryName = file[1];
zipEntryName = file[file.length - 1];
System.out.println("ZIP UPDATED " + zipEntryName + "");
// _location=_location+"/"+file[0]+"/";
String l = "";
for (int i = 0; i < file.length - 1; i++) {
l = l + "/" + file[i];
}
// System.out.println("TESTTTTTTTT " + l + "");
// loc = _location + "/" + file[0];
// loc = _location + "/" + l;
LOC = _location + "/" + l;
File thumb = new File(LOC);
if (!thumb.exists()) {
thumb.mkdir();
}
System.out.println("createddd dir ");
System.out.println("createddd dir loc " + loc);
} else {
System.out.println("create dir ");
System.out.println("HERE _location111: : : : " + _location);
System.out.println("HERE zipEntryName1111 : : : : /" + zipEntryName);
// File thumb = new File(_location+"/"+zipEntryName);
File thumb = new File(LOC + "/" + zipEntryName);
if (!thumb.exists()) {
thumb.mkdir();
}
}
}
System.out.println("HERE _location: : : : " + _location);
System.out.println("HERE zipEntryName : : : : /" + zipEntryName);
System.out.println("HERE loc : : : : /" + loc);
// File file = new File(_location + "/" + zipEntryName);
File file = new File(LOC + "/" + zipEntryName);
if (file.exists()) {
} else {
if (zipEntry.isDirectory()) {
file.mkdirs();
} else {
byte buffer[] = new byte[BUFFER_SIZE];
FileOutputStream fileOutputStream = new FileOutputStream(file);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream, BUFFER_SIZE);
int count;
while ((count = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
bufferedOutputStream.write(buffer, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
}
}
zipInputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void unZipIt(String zipFile, String outputFolder) {
byte[] buffer = new byte[1024];
//mm System.out.println("ZIP FILE "+zipFile+"");
//mm System.out.println("outputFolder FILE "+outputFolder+"");
try {
//create output directory is not exists
File folder = new File(outputFolder);
if (!folder.exists()) {
folder.mkdir();
}
//get the zip file content
ZipInputStream zis =
new ZipInputStream(new FileInputStream(zipFile));
//get the zipped file list entry
ZipEntry ze = zis.getNextEntry();
while (ze != null) {
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
//mm System.out.println("file unzip : " + newFile.getAbsoluteFile());
//create all non exists folders
//else you will hit FileNotFoundException for compressed folder
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
}
I have this Java method to upload a file. I am trying to cater for users trying to upload a folder by compressing that folder into a zip file and upload it instead. For some reason in my case file.isDirectory() and file.isFile() are not working correctly.. even though the filename does not contain any extension, file.isFile() is returning true and isDirectory() returns false. Also directory.list() is also acting weird by returning null.
What can be the problem? Am I doing something wrong?
public File uploadFile(FileItem item, String filename, int ticket_id) throws IOException
{
FileOutputStream out = null;
InputStream fileContent = null;
File file = null;
try
{
//fullpath returns C://MyDocuments//zerafbe//Documents//apache-tomcat-7.0.29//webapps//attachments//t50\test
StringBuffer fullPath = new StringBuffer();
fullPath.append(Attachment.attachments_path);
fullPath.append("t");
fullPath.append(Integer.toString(ticket_id));
fullPath.append(File.separator);
fullPath.append(filename);
System.out.println("filename " + filename);
file = new File(fullPath.toString());
if (!file.exists())
{
// if directory does not exist, create it
file.getParentFile().mkdirs();
}
if (file.isFile())
{
// if file is not a folder
out = new FileOutputStream(file);
fileContent = item.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
// read all the file and write it to created file
while ((read = fileContent.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
}
else if (file.isDirectory())
{
ZipFile appZip = new ZipFile(fullPath.toString());
appZip.generateFileList(file);
appZip.zipIt(filename + ".zip");
}
}
catch (FileNotFoundException e)
{
LogFile.logError("[FileUpload.uploadFile()] " + e.getMessage());
}
catch (IOException e1)
{
LogFile.logError("[FileUpload.uploadFile()] " + e1.getMessage());
}
finally
{
if (out != null)
{
out.close();
}
if (fileContent != null)
{
fileContent.close();
}
}
return file;
}
This is the ZipFile class I am using
public class ZipFile
{
List<String> fileList = null;
String source_folder = "";
public ZipFile(String source_folder)
{
fileList = new ArrayList<String>();
this.source_folder = source_folder;
}
public void zipIt(String zipFile)
{
byte[] buffer = new byte[1024];
String source = "";
try
{
try
{
source = source_folder.substring(source_folder.lastIndexOf("\\") + 1, source_folder.length());
}
catch(Exception e)
{
source = source_folder;
}
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
for (String file : this.fileList)
{
ZipEntry ze = new ZipEntry(source + File.separator + file);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(source_folder + File.separator + file);
int len;
while ((len = in.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}
in.close();
}
zos.closeEntry();
//remember close it
zos.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
public void generateFileList(File node)
{
// add file only
if(node.isFile())
{
fileList.add(generateZipEntry(node.toString()));
}
if(node.isDirectory())
{
String[] subNode = node.list();
if (subNode != null) {
for(String filename : subNode)
{
generateFileList(new File (node, filename));
}
}
}
}
private String generateZipEntry(String path)
{
return path.substring(source_folder.length() + 1, path.length());
}
}
file.list() is being done in the generateFileList method in ZipFile class. I know this is returning null since I tried detecting whether the file is a folder or a file by using filename.indexOf(".") instead of isDirectory() and isFile() since they were not working. But I wish I had an explanation for this.
Thanks for your help!
if (!file.exists()) {
// if directory does not exist, create it
file.mkdirs();
}
will create directory and test file.isDirectory() will return true
It could be a problem with the path?
C://MyDocuments//zerafbe//Documents//apache-tomcat-7.0.29//webapps//attachments//t50\test
You are mixing backslash with slash...
I tested your code block
ZipFile appZip = new ZipFile(file.toString());
appZip.generateFileList(file);
appZip.zipIt(filename + ".zip");
with a local folder and it's working perfectly. I think you are passing a invalid path. This may be the cause isFile or isDirectory methods are acting strangely. Try to add a validation statement at the starting of generateFileList method using File API:
if(!node.exists) {
// return some flag to signify error OR throw a suitable Exception
}
This should work.
public String compressData(String srcDir) {
String zipFile = srcDir+".zip";
try {
// create byte buffer
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
File dir = new File(srcDir);
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println("Adding file: " + files[i].getName());
FileInputStream fis = new FileInputStream(files[i]);
// begin writing a new ZIP entry, positions the stream to the start of the entry data
zos.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
fis.close();
}
// close the ZipOutputStream
zos.close();
}
catch (IOException ioe) {
System.out.println("Error creating zip file" + ioe);
}
return zipFile;
}
I'm trying to extract .zip files and I'm using this code:
String zipFile = Path + FileName;
FileInputStream fin = new FileInputStream(zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
UnzipCounter++;
if (ze.isDirectory()) {
dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(Path
+ ze.getName());
while ((Unziplength = zin.read(Unzipbuffer)) > 0) {
fout.write(Unzipbuffer, 0, Unziplength);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
but the problem is that, while debugging, when the code reaches the while(!=null) part, the zin.getNextEntry() is always null so it doesnt extract anything..
The .zip file is 150kb.. How can I fix this?
The .zip exists
Code I use to dl the .zip:
URL=intent.getStringExtra("DownloadService_URL");
FileName=intent.getStringExtra("DownloadService_FILENAME");
Path=intent.getStringExtra("DownloadService_PATH");
File PathChecker = new File(Path);
try{
if(!PathChecker.isDirectory())
PathChecker.mkdirs();
URL url = new URL(URL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
lenghtOfFile/=100;
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(Path+FileName);
byte data[] = new byte[1024];
long total = 0;
int count = 0;
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
total += count;
notification.setLatestEventInfo(context, contentTitle, "جاري تحميل ملف " + FileName + " " + (total/lenghtOfFile), contentIntent);
mNotificationManager.notify(1, notification);
}
output.flush();
output.close();
input.close();
You might have run into the following problem, which occurs, when reading zip files using a ZipInputStream: Zip files contain entries and additional structure information in a sequence. Furthermore, they contain a registry of all entries at the very end (!) of the file. Only this registry does provide full information about the correct zip file structure. Therefore, reading a zip file in a sequence, by using a stream, sometimes results in a "guess", which can fail. This is a common problem of all zip implementations, not only for java.util.zip. Better approach is to use ZipFile, which determines the structure from the registry at the end of the file. You might want to read http://commons.apache.org/compress/zip.html, which tells a little more details.
If the Zip is placed in the same directory as this exact source, named "91.zip", it works just fine.
import java.io.*;
import java.util.zip.*;
class Unzip {
public static void main(String[] args) throws Exception {
String Path = ".";
String FileName = "91.zip";
File zipFile = new File(Path, FileName);
FileInputStream fin = new FileInputStream(zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
int UnzipCounter = 0;
while ((ze = zin.getNextEntry()) != null) {
UnzipCounter++;
//if (ze.isDirectory()) {
// dirChecker(ze.getName());
//} else {
byte[] Unzipbuffer = new byte[(int) pow(2, 16)];
FileOutputStream fout = new FileOutputStream(
new File(Path, ze.getName()));
int Unziplength = 0;
while ((Unziplength = zin.read(Unzipbuffer)) > 0) {
fout.write(Unzipbuffer, 0, Unziplength);
}
zin.closeEntry();
fout.close();
//}
}
zin.close();
}
}
BTW
what is the language in that MP3, Arabic?
I had to alter the source to get it to compile.
I used the File constructor that takes two String arguments, to insert the correct separator automatically.
Try this code:-
private boolean extractZip(String pathOfZip,String pathToExtract)
{
int BUFFER_SIZE = 1024;
int size;
byte[] buffer = new byte[BUFFER_SIZE];
try {
File f = new File(pathToExtract);
if(!f.isDirectory()) {
f.mkdirs();
}
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(pathOfZip), BUFFER_SIZE));
try {
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
String path = pathToExtract +"/"+ ze.getName();
if (ze.isDirectory()) {
File unzipFile = new File(path);
if(!unzipFile.isDirectory()) {
unzipFile.mkdirs();
}
}
else {
FileOutputStream out = new FileOutputStream(path, false);
BufferedOutputStream fout = new BufferedOutputStream(out, BUFFER_SIZE);
try {
while ( (size = zin.read(buffer, 0, BUFFER_SIZE)) != -1 ) {
fout.write(buffer, 0, size);
}
zin.closeEntry();
}catch (Exception e) {
Log.e("Exception", "Unzip exception 1:" + e.toString());
}
finally {
fout.flush();
fout.close();
}
}
}
}catch (Exception e) {
Log.e("Exception", "Unzip exception2 :" + e.toString());
}
finally {
zin.close();
}
return true;
}
catch (Exception e) {
Log.e("Exception", "Unzip exception :" + e.toString());
}
return false;
}
This code works fine for me. Perhaps you need to check that the zipFile String is valid?
String zipFile = "C:/my.zip";
FileInputStream fin = new FileInputStream(zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
System.out.println("got entry " + ze);
}
zin.close();
produced valid results on a 3.3Mb zip file.
This code seems to work correctly for me.
Are you sure that your zip file is a valid zip file? If the file does not exist or is not readable then you will get a FileNotFoundException, but if the file is empty or not a valid zip file, then you will get ze == null.
while ((ze = zin.getNextEntry()) != null) {
The zip that you specify isn't a valid zip file. The size of the entry is 4294967295
while ((ze = zin.getNextEntry()) != null) {
System.out.println("ze=" + ze.getName() + " " + ze.getSize());
UnzipCounter++;
This gives:
ze=595.mp3 4294967295
...
Exception in thread "main" java.util.zip.ZipException: invalid entry size (expected 4294967295 but got 341297 bytes)
at java.util.zip.ZipInputStream.readEnd(ZipInputStream.java:386)
at java.util.zip.ZipInputStream.read(ZipInputStream.java:156)
at java.io.FilterInputStream.read(FilterInputStream.java:90)
at uk.co.farwell.stackoverflow.ZipTest.main(ZipTest.java:29)
Try your code with a valid zip file.
I know it's late for answer but anyway ..
I think the problem is in
if(!PathChecker.isDirectory())
PathChecker.mkdirs();
it should be
if(!PathChecker.getParentFile().exists())
PathChecker.getParentFile().mkdirs();
Unzipping files on android seems to be dreadfully slow. At first I thought this was just the emulator but it appears to be the same on the phone. I've tried different compression levels, and eventually dropped down to storage mode but it still takes ages.
Anyway, there must be a reason! Does anyone else have this problem? My unzip method looks like this:
public void unzip()
{
try{
FileInputStream fin = new FileInputStream(zipFile);
ZipInputStream zin = new ZipInputStream(fin);
File rootfolder = new File(directory);
rootfolder.mkdirs();
ZipEntry ze = null;
while ((ze = zin.getNextEntry())!=null){
if(ze.isDirectory()){
dirChecker(ze.getName());
}
else{
FileOutputStream fout = new FileOutputStream(directory+ze.getName());
for(int c = zin.read();c!=-1;c=zin.read()){
fout.write(c);
}
//Debug.out("Closing streams");
zin.closeEntry();
fout.close();
}
}
zin.close();
}
catch(Exception e){
//Debug.out("Error trying to unzip file " + zipFile);
}
}
I don't know if unzipping on Android is slow, but copying byte for byte in a loop is surely slowing it down even more. Try using BufferedInputStream and BufferedOutputStream - it might be a bit more complicated, but in my experience it is worth it in the end.
BufferedInputStream in = new BufferedInputStream(zin);
BufferedOutputStream out = new BufferedOutputStream(fout);
And then you can write with something like that:
byte b[] = new byte[1024];
int n;
while ((n = in.read(b,0,1024)) >= 0) {
out.write(b,0,n);
}
Thanks for the solution Robert.
I modified my unzip method and now it takes only a few seconds instead of 2 minutes.
Maybe someone's interested in my solution. So here you go:
public void unzip() {
try {
FileInputStream inputStream = new FileInputStream(filePath);
ZipInputStream zipStream = new ZipInputStream(inputStream);
ZipEntry zEntry = null;
while ((zEntry = zipStream.getNextEntry()) != null) {
Log.d("Unzip", "Unzipping " + zEntry.getName() + " at "
+ destination);
if (zEntry.isDirectory()) {
hanldeDirectory(zEntry.getName());
} else {
FileOutputStream fout = new FileOutputStream(
this.destination + "/" + zEntry.getName());
BufferedOutputStream bufout = new BufferedOutputStream(fout);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zipStream.read(buffer)) != -1) {
bufout.write(buffer, 0, read);
}
zipStream.closeEntry();
bufout.close();
fout.close();
}
}
zipStream.close();
Log.d("Unzip", "Unzipping complete. path : " + destination);
} catch (Exception e) {
Log.d("Unzip", "Unzipping failed");
e.printStackTrace();
}
}
public void hanldeDirectory(String dir) {
File f = new File(this.destination + dir);
if (!f.isDirectory()) {
f.mkdirs();
}
}
Using above ideas and ideas from some other sources I have created this class
Create this new class
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import android.util.Log;
public class DecompressFast {
private String _zipFile;
private String _location;
public DecompressFast(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
BufferedOutputStream bufout = new BufferedOutputStream(fout);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zin.read(buffer)) != -1) {
bufout.write(buffer, 0, read);
}
bufout.close();
zin.closeEntry();
fout.close();
}
}
zin.close();
Log.d("Unzip", "Unzipping complete. path : " +_location );
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
Log.d("Unzip", "Unzipping failed");
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
USAGE
just pass your file location of zip file and your destination Location to this class
example
String zipFile = Environment.getExternalStorageDirectory() + "/the_raven.zip"; //your zip file location
String unzipLocation = Environment.getExternalStorageDirectory() + "/unzippedtestNew/"; // unzip location
DecompressFast df= new DecompressFast(zipFile, unzipLocation);
df.unzip();
Dont Forget to add following permissions in manifest(also Run time permission if version higher than marshmellow)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
hope this helps
The URL that helped me learn how to zip and unzip can be found here.
I used that URL in conjuction with user3203118's answer above for unzipping. This is for future references for people who run in to this issue and need help solving it.
Below is the ZipManager code I am using:
public class ZipManager {
private static final int BUFFER = 80000;
public void zip(String[] _files, String zipFileName) {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(zipFileName);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
byte data[] = new byte[BUFFER];
for (int i = 0; i < _files.length; i++) {
Log.v("Compress", "Adding: " + _files[i]);
FileInputStream fi = new FileInputStream(_files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(_files[i].substring(_files[i]
.lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void unzip(String _zipFile, String _targetLocation) {
// create target location folder if not exist
dirChecker(_targetLocation);
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
// create dir if required while unzipping
if (ze.isDirectory()) {
dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(
_targetLocation + "/" + ze.getName());
BufferedOutputStream bufout = new BufferedOutputStream(fout);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zin.read(buffer)) != -1) {
bufout.write(buffer, 0, read);
}
zin.closeEntry();
bufout.close();
fout.close();
}
}
zin.close();
} catch (Exception e) {
System.out.println(e);
}
}
private void dirChecker(String dir) {
File f = new File(dir);
if (!f.isDirectory()) {
f.mkdirs();
}
}
}
Just call this method and it will give you much better performance..
public boolean unzip(Context context) {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
BufferedInputStream in = new BufferedInputStream(zin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if (ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location
+ ze.getName());
BufferedOutputStream out = new BufferedOutputStream(fout);
byte b[] = new byte[1024];
for (int c = in.read(b,0,1024); c != -1; c = in.read()) {
out.write(b,0,c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
return true;
} catch (Exception e) {
Log.e("Decompress", "unzip", e);
return false;
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if (!f.isDirectory()) {
f.mkdirs();
}
}
In case of using BufferedOutputStream be sure to flush it. If you do not do it, size smaller than buffer will not be unzipped properly
if (ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location
+ ze.getName());
BufferedOutputStream out = new BufferedOutputStream(fout);
byte buffer[] = new byte[1024];
for (int c = in.read(buffer,0,1024); c != -1; c = in.read()) {
out.write(buffer,0,c);
}
out.flush();//flush it......
zin.closeEntry();
fout.close();
}