Android unzip zip file from internal storage - android

I am downloading zip file from server to internal storage. And after downloading I want to unzip that file in internal storage itself. My file is downloaded to internal storage and I can see that but while unzip I am not able to read it. Below is my unzipfile() method. Can anyone tell where I am going wrong?
public void unzipfile()
{
try {
Log.d("unzipiing","unzipping");
ContextWrapper cw = new ContextWrapper(context);
String name_="foldername"; //Folder name in device android/data/
File directory = cw.getDir(name_, Context.MODE_PRIVATE);
File mypath=new File(directory,"dwnld");
FileOutputStream fout = new FileOutputStream(mypath);
File yourFile = new File(directory,"dwnld.zip");
Log.d("unzipiing","filepath -" + yourFile.getPath());
FileInputStream fin = new FileInputStream(yourFile.getPath());
ZipInputStream zin = new ZipInputStream(fin);
Log.d("unzipiing","zin size -" + zin.available());
// zin.available() give -1 in console log
BufferedInputStream in = new BufferedInputStream(zin);
BufferedOutputStream out = new BufferedOutputStream(fout);
byte b[] = new byte[zin.available()];
int n;
Log.d("unzip","n - " + in.read(b,0,1024));
while ((n = in.read(b,0,1024)) >= 0) {
out.write(b,0,n);
Log.d("unzip byte"," - " + n);
}
out.flush();
out.close();
in.close();
fin.close();
zin.close();
}
catch (Exception e){
}
}

<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
use this method for unzip
public void unzip(String _zipFile, String _targetLocation) {
//create target location folder if not exist
dirChecker(_targetLocatioan);
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());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch (Exception e) {
System.out.println(e);
}
}
check the path
public void dirChecker(String filepath)
{
File file = new File(filePath);
if(file.exists())
//Do something
else
// Do something else.
}

Related

Zip Path Traversal Vulnerability Alert (Android)

I am getting the "Zip Path Traversal Vulnerability" alert in Google Play Console.
I followed official Google docs (https://support.google.com/faqs/answer/9294009) to fix it but the alert is still there.
Here is the code that handles unzipping. I have even tested using a zip file that has the vulnerability described and the exception is raised as expected.
What am I missing?
private boolean unpackZip(File zipFile, File outputDirectory, IOnResult<Integer> progress) {
InputStream is;
ZipInputStream zis;
ZipInputStream zisCount;
try {
int totalEntries = 0;
int entryCount = 0;
String filename;
ZipEntry ze;
is = new FileInputStream(zipFile);
zisCount = new ZipInputStream(new BufferedInputStream(is));
while ((ze = zisCount.getNextEntry()) != null) {
// Fixing a Zip Path Traversal Vulnerability
// (https://support.google.com/faqs/answer/9294009)
filename = ze.getName();
File targetFile = new File(outputDirectory, filename);
String targetPath = targetFile.getCanonicalPath();
if (!targetPath.startsWith(outputDirectory.getCanonicalPath())) {
throw new SecurityException("Archive security error");
}
// -----------------------------------------------------------------------------
totalEntries++;
zisCount.closeEntry();
}
zisCount.close();
is = new FileInputStream(zipFile);
zis = new ZipInputStream(new BufferedInputStream(is));
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null) {
filename = ze.getName();
// Fixing a Zip Path Traversal Vulnerability (https://support.google.com/faqs/answer/9294009)
File targetFile = new File(outputDirectory, filename);
String targetPath = targetFile.getCanonicalPath();
if (!targetPath.startsWith(outputDirectory.getCanonicalPath())) {
throw new SecurityException("Archive security error");
}
// Need to create directories if not exists, or
// it will generate an Exception...
if (ze.isDirectory()) {
File fmd = new File(outputDirectory, filename);
fmd.mkdirs();
continue;
}
File outputFile = new File(outputDirectory, filename);
for( File parentFile = outputFile.getParentFile(); !parentFile.exists(); parentFile = parentFile.getParentFile() )
{
parentFile.mkdir();
}
FileOutputStream fout = new FileOutputStream(outputFile);
Log.d(TAG, "unzipped " + filename);
while ((count = zis.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
entryCount++;
}
zis.close();
} catch (IOException | SecurityException e) {
Log.e(TAG, "unpackZip", e);
return false;
}
return true;
}

unzipped in target directory

I want to unzip to zip file in same directory,When I try below code it unzipped below target directory not in target folder,how can I unzipped all files in target directory in android
public static void unzip(String zipFilePath, String destDir) {
BufferedOutputStream bufferedOutputStream = null;
FileInputStream fileInputStream;
File dest_file = new File(destDir);
//dest_file.mkdirs(); // creates if destination directory not existed
try {
fileInputStream = new FileInputStream(zipFilePath);
ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(fileInputStream));
ZipEntry zipEntry;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String zipEntryName = zipEntry.getName();
File file = new File(destDir + zipEntryName);
if (file.exists()) {
} else if (zipEntry.isDirectory()) {
file.mkdirs();
} else {
byte buffer[] = new byte[1024];
FileOutputStream fileOutputStream = new FileOutputStream(file);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream, 1024);
int count;
while ((count = zipInputStream.read(buffer, 0, 1024)) != -1) {
bufferedOutputStream.write(buffer, 0, count);
}
bufferedOutputStream.flush();
bufferedOutputStream.close();
}
}
zipInputStream.close();
} catch (Exception e) {
Log.e("Decompress", "unzip", e);
}
}
I call unzip File
String source = /storage/emulated/0/Android/data/com.kocsistem.pixageoneandroid/files/Contents/widgetContent + "/" + "123.zip";
String target = /storage/emulated/0/Android/data/com.kocsistem.pixageoneandroid/files/Contents/widgetContent ;
Utils.unzip(source, target);

Android unzip database file from assets folder

I am building the app which i want to unzip the database file from assets. But i am getting this errorjava.io.FileNotFoundException: /file:/android_asset/kjv.zip: open failed: ENOENT (No such file or directory).
I am using this code for unzip the file,
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());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch (Exception e) {
Log.e("error", e + "");
}
}
private void dirChecker(String dir) {
File f = new File(dir);
if (!f.isDirectory()) {
f.mkdirs();
}
}
And call using this,
Uri path = Uri.parse("file:///android_asset/kjv.zip");
inputPath = path.toString();
ZipManager zipManager = new ZipManager();
zipManager.unzip(inputPath, outputPath);
I tried, but it was error every time. Can't understand what is the problem. If you have alternative solution then please suggest me. Help me. Thank you.

How to unzip files do a specific folder in Android?

I am unziping a file based in the official documentation and some examples. My current implementation unzip the file in the same directory where is the zip file. I'd like to unzip to a specific directory in my device. How can I do this? The ZipInputStream allow this feature or do I have to unzip and then move the files to the desired folder?
This is my code:
public static boolean unpackZip(String path, String zipname) {
InputStream is;
ZipInputStream zis;
try {
String filename;
is = new FileInputStream(path + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null) {
filename = ze.getName();
if (ze.isDirectory()) {
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fout = new FileOutputStream(path + filename);
while ((count = zis.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
You need to create the folder by splitting the string:
if (filename.contains("/")){
String[] folders = filename.split("/");
for (String item : folders)
{
File fmd = new File(path + item);
if (!item.contains(".") && !fmd.exists()){
fmd.mkdirs();
Log.d("created folder", item);
}
}
}
FULL CODE:
public static boolean unpackZip(String path, String zipname) {
InputStream is;
ZipInputStream zis;
try {
String filename;
is = new FileInputStream(path + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null) {
filename = ze.getName();
if (ze.isDirectory()) {
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
//ADD THIS//
if (filename.contains("/")){
String[] folders = filename.split("/");
for (String item : folders)
{
File fmd = new File(path + item);
if (!item.contains(".") && !fmd.exists()){
fmd.mkdirs();
Log.d("created folder", item);
}
}
}
FileOutputStream fout = new FileOutputStream(path + filename);
while ((count = zis.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
Where you open the file as in File fmd = new File(path + filename); and FileOutputStream fout = new FileOutputStream(path + filename); you can simply prepend the target directory as path + filename is simply the path to the file. I'm not sure what you are passing in as path in this case, I assume the path to the zip file, if you wish to extract elsewhere you need to pass in another variable with the target. Something like:
public static boolean unpackZip(String path, String zipname, String outputPath) {
InputStream is;
ZipInputStream zis;
try {
String filename;
is = new FileInputStream(path + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null) {
filename = ze.getName();
if (ze.isDirectory()) {
File fmd = new File(outputPath + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fout = new FileOutputStream(outputPath + filename);
while ((count = zis.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
Specify a target directory as a parameter. Apart this, your code seems ok.
public static boolean unpackZip(String path, String zipname, String targetDirectory) {
InputStream is;
ZipInputStream zis;
try {
String filename;
is = new FileInputStream(path + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null) {
filename = ze.getName();
if (ze.isDirectory()) {
File fmd = new File(targetDirectory + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fout = new FileOutputStream(targetDirectory + filename);
while ((count = zis.read(buffer)) != -1) {
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}

File writing in external storage device is not working

I tried writing a file to my android phone using phonegap ui.
I have given the write permission and i tried by using getExternalStorageDirectory() and by giving the absolute path. But still not able to write it.
s1 is the name of the file that i am writing in the external storage
Environment.getExternalStorageState();
//File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),"/Android/");
File file = new File("/mnt/sdcard"+ File.separator + "Android" + File.separator);
if (!file.exists()) {
if (!file.mkdirs()) {
Log.e("TravellerLog :: ", "Problem creating Folder");
}
}
Environment.getExternalStorageState();
File outputFile = new File(file, s1);
FileOutputStream fileoutputstream = new FileOutputStream(outputFile);
byte abyte0[] = new byte[1024];
for (int i = 0; (i = inputstream.read(abyte0)) > 0;)
fileoutputstream.write(abyte0, 0, i);
fileoutputstream.close();
inputstream.close();
I wrote a quick working demo of writing a file to the external storage.
If this still doesn't work maybe it is a phonegap specific issue.
Hope this helps:
InputStream is = null;
OutputStream os = null;
byte[] buffer = new byte[2048];
int bytes_read = 0;
File inputFile = new File("/init.rc");
File outputFile = new File(Environment.getExternalStorageDirectory() + "/testfile");
try
{
is = new FileInputStream(inputFile);
os = new FileOutputStream(outputFile);
while ((bytes_read = is.read(buffer)) != -1)
{
os.write(buffer, 0, bytes_read);
}
}
catch (Exception ignore) {}
finally
{
try
{
is.close();
}
catch (Exception ignore) {}
try
{
os.close();
}
catch (Exception ignore) {}
}
if (outputFile.exists())
{
Toast.makeText(this, "Success!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(this, "Failure!", Toast.LENGTH_LONG).show();
}

Categories

Resources