Extrakting邮编到SD卡很慢。如何优化性能? [英] Extrakting Zip to SD-Card is very slow. How can i optimize performance?
问题描述
我的应用程序下载约350文件的zip。的JPG和HTML文件的组合。我写这样做的功能工作得很好,但解压需要永远。 起初我以为原因可能是写入SD卡是缓慢的。但是当我解压同一个zip用我的手机上的其它应用程序,它工作得更快。是有什么我可以做优化呢?
my app downloads a zip with about 350 files. A mix of JPG and HTML files. The function i wrote to do it works just fine but the unzipping takes for ever. At first i thought the reason might be that writing to the sd-card is slow. but when i unzip the same zip with an other app on my phone it works much faster. is there anything that i could do to optimize it?
这里是code:
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();
}
}
由于CommonsWare我修改了code是这样的:
thanks to CommonsWare i modified my code like this:
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();
大的性能差异。 非常感谢。
big performance difference. Thanks a lot.
推荐答案
正在读取和写入一个字节的时间。考虑读取和写入较大块的时间。
You are reading and writing a byte at a time. Consider reading and writing a larger block at a time.
这篇关于Extrakting邮编到SD卡很慢。如何优化性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!