Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zip the files in android

Tags:

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.

like image 419
brig Avatar asked Jan 19 '23 08:01

brig


1 Answers

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) { 
  e.printStackTrace(); 
} 

}

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

  <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
like image 118
Pir Fahim Shah Avatar answered Jan 29 '23 12:01

Pir Fahim Shah