这些权限是为了将数据存储到您的设备存储中而需要的。
Mainfest.xml文件
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
请求写外置存储权限(更新于2018年10月04日)
public static void verifyStoragePermissions(Activity activity) {
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
Zip函数
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();
}
}
使用 Zip 函数
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);
解压函数
public void unzip(String _zipFile, String _targetLocation) {
dirChecker(_targetLocatioan);
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
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);
}
}
private void dirChecker(String dir) {
File f = new File(dir);
if (!f.isDirectory()) {
f.mkdirs();
}
}
使用解压功能
ZipManager zipManager = new ZipManager();
zipManager.unzip(inputPath + inputFile, outputPath);
[来源:http://stacktips.com/tutorials/android/how-to-programmatically-zip-and-unzip-file-in-android]
本教程将介绍如何在Android应用程序中以编程方式创建ZIP文件和解压缩文件。
在Android开发中,我们可能需要压缩或解压缩文件,例如,在发送电子邮件附件之前,我们可以将多个文件打包到一个ZIP文件中。 在这种情况下,我们可以使用Java的ZipOutputStream类来创建ZIP文件,并使用ZipInputStream类来解压缩ZIP文件。
以下是创建ZIP文件的步骤:
1. 创建ZipOutputStream对象并将其连接到要写入的文件。
2. 使用putNextEntry()方法为每个文件创建新条目。
3. 使用write()方法将文件内容写入输出流。
4. 使用closeEntry()方法关闭当前条目。
以下是解压缩ZIP文件的步骤:
1. 创建ZipInputStream对象并将其连接到要读取的文件。
2. 使用getNextEntry()方法获取下一个条目。
3. 使用read()方法从输入流中读取数据。
4. 使用closeEntry()方法关闭当前条目。
以上就是在Android应用程序中以编程方式创建ZIP文件和解压缩文件的完整过程。