很多时候需要把一个预制的zip文件解压到根目录,下面是一个实例代码:
private static final int BUFFER_SIZE = 4096;
public static void unZip(String zipFilePath, String targetDir) throws IOException {
File destDir = new File(targetDir);
if (!destDir.exists()) {
destDir.mkdirs();
}
try (FileInputStream fis = new FileInputStream(zipFilePath);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis))) {
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
String entryName = entry.getName();
File file = new File(destDir, entryName);
if (entry.isDirectory()) {
file.mkdirs();
} else {
extractFile(zis, file);
}
zis.closeEntry();
}
}
}
private static void extractFile(ZipInputStream zis, File file) throws IOException {
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
try (FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER_SIZE)) {
byte[] buffer = new byte[BUFFER_SIZE];
int read;
while ((read = zis.read(buffer)) != -1) {
bos.write(buffer, 0, read);
}
}
}
使用实例:
unZip("/system/media/xxx.zip", "/storage/emulated/0/");
包自己导入一下就行了