我需要以编程方式压缩 txt 文件。
我已经在 files 创建了文本文件directory(context.getFilesDirectory())
,
我想压缩文本文件并将压缩文件添加到 Intent 对象中。
请给我一段代码来说明如何在android中压缩文件。
如果您在 SDCard 中有一个文件夹,并且想要创建它的 zip,那么只需将此代码复制并粘贴到您的项目中,它就会为您提供一个 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();
}
}
还可以使用此代码在 android-manifest.xml 中添加权限
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)