一、AndroidManifest.xml 添加 sd 卡读写权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
二、方法如下:
public void unzipFile(String zipPtath, String outputDirectory)throws IOException {
Log.i(TAG,"开始解压的文件: " + zipPtath + "\n" + "解压的目标路径:" + outputDirectory );
File file = new File(outputDirectory);
if (!file.exists()) {
file.mkdirs();
}
InputStream inputStream = new FileInputStream(zipPtath); ;
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
ZipEntry zipEntry = zipInputStream.getNextEntry();
byte[] buffer = new byte[1024 * 1024];
int count = 0;
while (zipEntry != null) {
Log.i(TAG,"解压文件 入口 1: " +zipEntry );
if (!zipEntry.isDirectory()) {
String fileName = zipEntry.getName();
Log.i(TAG,"解压文件 原来 文件的位置: " + fileName);
fileName = fileName.substring(fileName.lastIndexOf("/") + 1);
Log.i(TAG,"解压文件 的名字: " + fileName);
file = new File(outputDirectory + File.separator + fileName);
file.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(file);
while ((count = zipInputStream.read(buffer)) > 0) {
fileOutputStream.write(buffer, 0, count);
}
fileOutputStream.close();
}
zipEntry = zipInputStream.getNextEntry();
Log.i(TAG,"解压文件 入口 2: " + zipEntry );
}
zipInputStream.close();
Log.i(TAG,"解压完成");
}
三、调用方法:
private String zipPtath = "/storage/emulated/0/testunzip/test.zip";
private String unzipPath = "/storage/emulated/0/testunzip/";
unzipFile(zipPtath,unzipPath);
|