我有一个包含两个文件的 zip 文件,一个 md5sum 和一个 3.5GB 的 .img 文件,它们由我的应用程序以 zip 文件的形式下载,然后需要在设备上解压缩。 目前我正在使用下面的内部类,它被测试为适用于更小的 zip 文件:
private class UnZip extends AsyncTask<Void, Integer, Integer> {
private String _zipFile;
private String _location;
private int per = 0;
public UnZip(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
protected Integer doInBackground(Void... params) {
try {
ZipFile zip = new ZipFile(_zipFile);
bar.setMax(zip.size());
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
// Here I am doing the update of my progress bar
Log.v("Decompress", "more " + ze.getName());
per++;
publishProgress(per);
FileOutputStream fout = new FileOutputStream(_location +ze.getName());
for (int c = zin.read(); c != -1; c = zin.read()) {
fout.write(c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
bar.setProgress(per); //Since it's an inner class, Bar should be able to be called directly
}
protected void onPostExecute(Integer... result) {
Log.i("UnZip" ,"Completed. Total size: "+result);
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
这很好用,并在解压缩每个文件时显示进度条,但是对于大文件来说这需要很长时间(在我的 Nexus 4 上大约每小时 20MB)。 我想看看有没有更好的方法来解压这么大的文件? (.img 文件实际上只有大约 1GB 的数据,其余的只是尾随零,以便以后有空间容纳更多数据)
或者也许不是按文件而是按 MB 数据或写入速度等查看进度的方法?从长远来看,向用户提供有关解压缩过程的更多信息将非常有用。
最佳答案
在某处添加以下内容:
public static void streamCopy(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[32 * 1024]; // play with sizes..
int readCount;
while ((readCount = in.read(buffer)) != -1) {
out.write(buffer, 0, readCount);
}
}
这是一个通用的标准代码,用于将输入流复制到输出流,并且在多个库中也可以找到。
然后在你的代码中使用它
} else {
// Here I am doing the update of my progress bar
Log.v("Decompress", "more " + ze.getName());
per++;
publishProgress(per);
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
streamCopy(zin, fout);
zin.closeEntry();
fout.close();
}
优点是您以更大的 block 而不是单个字节读取和写入,这大大加快了处理速度。
关于java - 在 Android 上解压缩大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17814707/