Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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=newString[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 functionpublicvoidzip(String[] files, String zipFile) 
 { 
    private String[] _files= files;
    private String _zipFile= zipFile;  

try  { 
  BufferedInputStreamorigin=null; 
  FileOutputStreamdest=newFileOutputStream(_zipFile); 

  ZipOutputStreamout=newZipOutputStream(newBufferedOutputStream(dest)); 

  byte data[] = newbyte[BUFFER]; 

  for(int i=0; i < _files.length; i++) { 
      Log.d("add:",_files[i]);
    Log.v("Compress", "Adding: " + _files[i]); 
    FileInputStreamfi=newFileInputStream(_files[i]); 
    origin = newBufferedInputStream(fi, BUFFER); 
    ZipEntryentry=newZipEntry(_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(); 
} 

}

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

<uses-permissionandroid:name="android.permission.WRITE_INTERNAL_STORAGE" />

Solution 2:

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:

dependencies {
compile'com.github.ghost1372:Mzip-Android:0.4.0'
}

here is the code to zip files:

Zip:

ZipArchivezipArchive=newZipArchive();
zipArchive.zip(targetPath,destinationPath,password);

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

Solution 3:

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<String> allFiles, String zipFileName)throws IOException
    {
        timeStampOfZipFile =newSimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime());
        App.mediaStorageDir.mkdirs();
        zippath = App.mediaStorageDir.getAbsolutePath() + "/" + zipFileName+ timeStampOfZipFile +  ".zip";
        try
        {
            if (newFile(zippath).exists())
            {
                newFile(zippath).delete();
            }
            //new File(zipFileName).delete(); // Delete if existsZipFilezipFile=newZipFile(zippath);
            ZipParameterszipParameters=newZipParameters();
            zipParameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            zipParameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            zipParameters.setPassword("Reset");

            if (allFiles.size() > 0)
            {
                for (String fileName : allFiles)
                {
                    Filefile=newFile(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

publicstaticfinalFilemediaStorageDir=newFile(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

<!-- == External Storage == --><uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"/><uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Post a Comment for "How To Zip The Files In Android"