not*_*tme 14 zip android extraction
我的应用程序下载了大约350个文件的zip.混合了JPG和HTML文件.我写的功能做得很好,但解压缩需要永远.起初我认为原因可能是写入SD卡很慢.但是当我用手机上的其他应用程序解压缩相同的拉链时,它的工作速度要快得多.我能做些什么来优化它?
这是代码:
private void extract() {
try {
FileInputStream inStream = new FileInputStream(targetFilePath);
ZipInputStream zipStream = new ZipInputStream(new BufferedInputStream(inStream));
ZipEntry entry;
ZipFile zip = new ZipFile(targetFilePath);
//i know the contents for the zip so i create the dirs i need in advance
new File(targetFolder).mkdirs();
new File(targetFolder + "META-INF").mkdir();
new File(targetFolder + "content").mkdir();
int extracted = 0;
while((entry = zipStream.getNextEntry()) != null) {
if (entry.isDirectory()) {
new File(targetFolder + entry.getName()).mkdirs();
} else {
FileOutputStream outStream = new FileOutputStream(targetFolder + entry.getName());
for (int c = zipStream.read(); c != -1; c = zipStream.read()) {
outStream.write(c);
}
zipStream.closeEntry();
outStream.close();
extracted ++;
}
publishProgress(""+(int)extracted*100/zip.size());
}
zipStream.close();
inStream.close();
//
new File(targetFilePath).delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
感谢CommonsWare我修改了我的代码:
int size;
byte[] buffer = new byte[2048];
FileOutputStream outStream = new FileOutputStream(targetFolder + entry.getName());
BufferedOutputStream bufferOut = new BufferedOutputStream(outStream, buffer.length);
while((size = zipStream.read(buffer, 0, buffer.length)) != -1) {
bufferOut.write(buffer, 0, size);
}
bufferOut.flush();
bufferOut.close();
Run Code Online (Sandbox Code Playgroud)
性能差异很大.非常感谢.