如何压缩android中的文件

bri*_*rig 4 android

我需要以编程方式压缩文本文件.

我已经在文件中创建了文本文件directory(context.getFilesDirectory()),
我想压缩文本文件并将压缩文件添加到Intent对象.

请给我一段代码来说明如何压缩android中的文件.

Pir*_*hah 6

如果您在SDCard中有一个文件夹,并且您想要创建它的拉链,那么只需将此代码复制并粘贴到您的项目中,它将为您提供一个zip文件夹.此代码将创建一个文件夹的zip文件,该文件夹仅包含不应嵌套文件夹的文件.您可以进一步修改自己.

 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(); 
} 
Run Code Online (Sandbox Code Playgroud)

}

还使用此代码在android-manifest.xml中添加权限

  <uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)