Android zip file java

How to Programmatically Zip and Unzip File in Android

This tutorial explains “How to Programmatically Zip and Unzip File in Android”. Zipping means writing (compress) data into zip files. Below code snippet will help you to zip and unzip files using a generic wrapper class that allows you to easily zip files in Android.

Why you need a Zip file?

  1. You couldn’t send multiple attachments using Intents to the Google Mail app. The quickest way around that was of course to compress all of the files into one (ZIP).
  2. For the applications that need to send multiple files to server, it is always easiest to create a zip file and send it across over network.

I have created both zip and unzip method inside a wrapper class called ZipManager . You may create the same way or you may like to use in your own way.

How to Zip files

Crete a sample android activity and add the following permission to application Mainfest.xml file. These persmissions are required to store data to your device storage.

You can use below code to create zip file. Just copy paste to make it work in your activity

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(); >>

BUFFER is used for limiting the buffer memory size while reading and writing data it to the zip stream

Читайте также:  Как извлечь элемент из массива python

_files array holds all the file paths that you want to zip

zipFileName is the name of the zip file.

You can use this in your activity

// declare an array for storing the files i.e the path // of your source files String[] s = new String[2]; // Type the path of the files in here s[0] = inputPath + "/image.jpg"; s[1] = inputPath + "/textfile.txt"; // /sdcard/ZipDemo/textfile.txt // first parameter is d files second parameter is zip file name ZipManager zipManager = new ZipManager(); // calling the zip function zipManager.zip(s, inputPath + inputFile);

You can get complete working eclipse project to end of this tutorial.

How to UnZip files

Now let us look into unzipping files. For unzipping you need to know the file path for .zip file and the path to the directory extract the files.

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); >>

You can use this method in your activity

ZipManager zipManager = new ZipManager(); zipManager.unzip(inputPath + inputFile, outputPath);

Download Complete Example

Here you can download complete eclipse project source code from GitHub.

Источник

How to zip and unzip the files?

How to zip and unzip the files which are all already in DDMS : data/data/mypackage/files/ I need a simple example for that. I’ve already search related to zip and unzip. But, no one example available for me. Can anyone tell some example. Advance Thanks.

4 Answers 4

Take a look at java.util.zip.* classes for zip functionality. I’ve done some basic zip/unzip code, which I’ve pasted below. Hope it helps.

public static void zip(String[] files, String zipFile) throws IOException < BufferedInputStream origin = null; ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile))); try < byte data[] = new byte[BUFFER_SIZE]; for (int i = 0; i < files.length; i++) < FileInputStream fi = new FileInputStream(files[i]); origin = new BufferedInputStream(fi, BUFFER_SIZE); try < ZipEntry entry = new ZipEntry(files[i].substring(files[i].lastIndexOf("/") + 1)); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) < out.write(data, 0, count); >> finally < origin.close(); >> > finally < out.close(); >> public static void unzip(String zipFile, String location) throws IOException < try < File f = new File(location); if(!f.isDirectory()) < f.mkdirs(); >ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile)); try < ZipEntry ze = null; while ((ze = zin.getNextEntry()) != null) < String path = location + ze.getName(); if (ze.isDirectory()) < File unzipFile = new File(path); if(!unzipFile.isDirectory()) < unzipFile.mkdirs(); >> else < FileOutputStream fout = new FileOutputStream(path, false); try < for (int c = zin.read(); c != -1; c = zin.read()) < fout.write(c); >zin.closeEntry(); > finally < fout.close(); >> > > finally < zin.close(); >> catch (Exception e) < Log.e(TAG, "Unzip exception", e); >> 

This worked great on Android 5.1. Thanks! I’ve added an answer here that is a modified version of yours which accepts List files and File zipFile as parameters, as it might be helpful for others.

The zip function brianestey provided works well, but the unzip function is very slow due to reading one byte at a time. Here is a modified version of his unzip function that utilizes a buffer and is much faster.

/** * Unzip a zip file. Will overwrite existing files. * * @param zipFile Full path of the zip file you'd like to unzip. * @param location Full path of the directory you'd like to unzip to (will be created if it doesn't exist). * @throws IOException */ public static void unzip(String zipFile, String location) throws IOException < int size; byte[] buffer = new byte[BUFFER_SIZE]; try < if ( !location.endsWith(File.separator) ) < location += File.separator; >File f = new File(location); if(!f.isDirectory()) < f.mkdirs(); >ZipInputStream zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile), BUFFER_SIZE)); try < ZipEntry ze = null; while ((ze = zin.getNextEntry()) != null) < String path = location + ze.getName(); File unzipFile = new File(path); if (ze.isDirectory()) < if(!unzipFile.isDirectory()) < unzipFile.mkdirs(); >> else < // check for and create parent directories if they don't exist File parentDir = unzipFile.getParentFile(); if ( null != parentDir ) < if ( !parentDir.isDirectory() ) < parentDir.mkdirs(); >> // unzip the file FileOutputStream out = new FileOutputStream(unzipFile, 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(); > finally < fout.flush(); fout.close(); >> > > finally < zin.close(); >> catch (Exception e) < Log.e(TAG, "Unzip exception", e); >> 

Thanks a lot. you save my time. its also useful when ze.getName() is not directly file but may contains folder and file within that folder. e.g. 1/abc.txt . Thanks you very much once again.

Using File instead of the file path String .

I have modified his zip method to accept a list of Files instead of file paths and an output zip File instead of a filepath, which might be helpful to others if that’s what they’re dealing with.

public static void zip( List files, File zipFile ) throws IOException < final int BUFFER_SIZE = 2048; BufferedInputStream origin = null; ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile))); try < byte data[] = new byte[BUFFER_SIZE]; for ( File file : files ) < FileInputStream fileInputStream = new FileInputStream( file ); origin = new BufferedInputStream(fileInputStream, BUFFER_SIZE); String filePath = file.getAbsolutePath(); try < ZipEntry entry = new ZipEntry( filePath.substring( filePath.lastIndexOf("/") + 1 ) ); out.putNextEntry(entry); int count; while ((count = origin.read(data, 0, BUFFER_SIZE)) != -1) < out.write(data, 0, count); >> finally < origin.close(); >> > finally < out.close(); >> 

This answer is based of brianestey, Ben, Giacomo Mattiuzzi, Joshua Pinter.

Functions rewritten to Kotlin and added functions for working with Uri.

import android.content.Context import android.net.Uri import java.io.* import java.util.zip.ZipEntry import java.util.zip.ZipInputStream import java.util.zip.ZipOutputStream private const val MODE_WRITE = "w" private const val MODE_READ = "r" fun zip(zipFile: File, files: List) < ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile))).use < outStream ->zip(outStream, files) > > fun zip(context: Context, zipFile: Uri, files: List) < context.contentResolver.openFileDescriptor(zipFile, MODE_WRITE).use < descriptor ->descriptor?.fileDescriptor?.let < ZipOutputStream(BufferedOutputStream(FileOutputStream(it))).use < outStream ->zip(outStream, files) > > > > private fun zip(outStream: ZipOutputStream, files: List) < files.forEach < file ->outStream.putNextEntry(ZipEntry(file.name)) BufferedInputStream(FileInputStream(file)).use < inStream ->inStream.copyTo(outStream) > > > fun unzip(zipFile: File, location: File) < ZipInputStream(BufferedInputStream(FileInputStream(zipFile))).use < inStream ->unzip(inStream, location) > > fun unzip(context: Context, zipFile: Uri, location: File) < context.contentResolver.openFileDescriptor(zipFile, MODE_READ).use < descriptor ->descriptor?.fileDescriptor?.let < ZipInputStream(BufferedInputStream(FileInputStream(it))).use < inStream ->unzip(inStream, location) > > > > private fun unzip(inStream: ZipInputStream, location: File) < if (location.exists() && !location.isDirectory) throw IllegalStateException("Location file must be directory or not exist") if (!location.isDirectory) location.mkdirs() val locationPath = location.absolutePath.let < if (!it.endsWith(File.separator)) "$it$" else it > var zipEntry: ZipEntry? var unzipFile: File var unzipParentDir: File? while (inStream.nextEntry.also < zipEntry = it >!= null) < unzipFile = File(locationPath + zipEntry. name) if (zipEntry. isDirectory) < if (!unzipFile.isDirectory) unzipFile.mkdirs() >else < unzipParentDir = unzipFile.parentFile if (unzipParentDir != null && !unzipParentDir.isDirectory) < unzipParentDir.mkdirs() >BufferedOutputStream(FileOutputStream(unzipFile)).use < outStream ->inStream.copyTo(outStream) > > > > 

Источник

How to zip the files in android

I have a requirement to zip the text files programatically. I have created text files at files directory(context.getFilesDirectory()) ,
I want zip the text files and add the zipped file to the Intent object. Please provide me a piece of code to how to zip the files in android.

3 Answers 3

If you have a FOLDER in SDCard and you want to create a zip of it, then simply copy and paste this code in your project and it will give you a zip Folder. This code will create a zip of the folder which only contains files no nested folder should be inside. You can further modify for your self.

 String []s=new String[2]; //declare an array for storing the files i.e the path of your source files s[0]="/mnt/sdcard/Wallpaper/pic.jpg"; //Type the path of the files in here s[1]="/mnt/sdcard/Wallpaper/Final.pdf"; // path of the second file zip((s,"/mnt/sdcard/MyZipFolder.zip"); //call the zip function public void zip(String[] files, String zipFile) < private String[] _files= files; private String _zipFile= zipFile; try < BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(_zipFile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; for(int i=0; i < _files.length; i++) < Log.d("add:",_files[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)

Also add permissions in android-manifest.xml using this code

@14bce109 yes ther is size for it, put BUFFER=1024 it will work, if could’t then inbox me , I will help you

If you want to compress files with password you can take a look at this library you need to add this lines to your build.gradle:

here is the code to zip files:

ZipArchive zipArchive = new ZipArchive(); zipArchive.zip(targetPath,destinationPath,password); 

//This Library is dead as it is not avaialable on github anymore

This is working code for zipping the files. You have to add all the file paths which you want to zip into the arrayList and send it as parameter to below function along with string name for zipfile you want.

 public String zipper(ArrayList allFiles, String zipFileName) throws IOException < timeStampOfZipFile =new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()); App.mediaStorageDir.mkdirs(); zippath = App.mediaStorageDir.getAbsolutePath() + "/" + zipFileName+ timeStampOfZipFile + ".zip"; try < if (new File(zippath).exists()) < new File(zippath).delete(); >//new File(zipFileName).delete(); // Delete if exists ZipFile zipFile = new ZipFile(zippath); ZipParameters zipParameters = new ZipParameters(); zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE); zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL); zipParameters.setPassword("Reset"); if (allFiles.size() > 0) < for (String fileName : allFiles) < File file = new File(fileName); zipFile.addFile(file, zipParameters); >> > catch (ZipException e) < e.printStackTrace(); >return zippath; > 

Here App.mediaStorageDir.mkdirs(); where mediaStorage is static final string in my App.class

public static final File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "yourAppFoler"); 

creates directory where the zip file will be saved. Result of function returns zip file path which can be used to attach to multipart entity for sending it to server(if you wish).

Requires run time permission for API>=marshmellow

Источник

Creating a ZIP file with Android

How can I create a ZIP file from an XML file? I want to take a backup of all my inbox messages in XML, and compress the XML file and store it on an SD card.

5 Answers 5

The following code solved my problem.

public class makeZip < static final int BUFFER = 2048; ZipOutputStream out; byte data[]; public makeZip(String name) < FileOutputStream dest=null; try < dest = new FileOutputStream(name); >catch (FileNotFoundException e) < // TODO Auto-generated catch block e.printStackTrace(); >out = new ZipOutputStream(new BufferedOutputStream(dest)); data = new byte[BUFFER]; > public void addZipFile (String name) < Log.v("addFile", "Adding: "); FileInputStream fi=null; try < fi = new FileInputStream(name); Log.v("addFile", "Adding: "); >catch (FileNotFoundException e) < // TODO Auto-generated catch block e.printStackTrace(); Log.v("atch", "Adding: "); >BufferedInputStream origin = new BufferedInputStream(fi, BUFFER); ZipEntry entry = new ZipEntry(name); try < out.putNextEntry(entry); Log.v("put", "Adding: "); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >int count; try < while((count = origin.read(data, 0, BUFFER)) != -1) < out.write(data, 0, count); //Log.v("Write", "Adding: "+origin.read(data, 0, BUFFER)); >> catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); Log.v("catch", "Adding: "); >try < origin.close(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> public void closeZip () < try < out.close(); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >> 

If you have a FOLDER in SDCard and you want to create a zip of it, then simply copy and paste this code in your project and it will give you a zip Folder. This code will create a zip of the folder which only contains files no nested folder should be inside. You can further modify for your self.

 String []s=new String[2]; //declare an array for storing the files i.e the path of your source files s[0]="/mnt/sdcard/Wallpaper/pic.jpg"; //Type the path of the files in here s[1]="/mnt/sdcard/Wallpaper/Final.pdf"; // path of the second file zip((s,"/mnt/sdcard/MyZipFolder.zip"); //call the zip function public void zip(String[] files, String zipFile) < private String[] _files= files; private String _zipFile= zipFile; try < BufferedInputStream origin = null; FileOutputStream dest = new FileOutputStream(_zipFile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); byte data[] = new byte[BUFFER]; for(int i=0; i < _files.length; i++) < Log.d("add:",_files[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)

Also add permissions in android-manifest.xml using this code

Источник

Оцените статью