如何在Android中以编程方式解压缩文件?
我需要一个小代码片段,从给定的.zip文件中解压缩几个文件,并根据压缩文件中的格式给出单独的文件。请发布您的知识并帮助我。
我需要一个小代码片段,从给定的.zip文件中解压缩几个文件,并根据压缩文件中的格式给出单独的文件。请发布您的知识并帮助我。
佩诺的版本优化了一下。性能的提高是显而易见的。
private boolean unpackZip(String path, String zipname)
{
InputStream is;
ZipInputStream zis;
try
{
String filename;
is = new FileInputStream(path + zipname);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null)
{
filename = ze.getName();
// Need to create directories if not exists, or
// it will generate an Exception...
if (ze.isDirectory()) {
File fmd = new File(path + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fout = new FileOutputStream(path + filename);
while ((count = zis.read(buffer)) != -1)
{
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
根据瓦西里·索钦斯基(Vasily Sochinsky)的答案,稍微调整了一下,并进行了一些小的修复:
public static void unzip(File zipFile, File targetDirectory) throws IOException {
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(new FileInputStream(zipFile)));
try {
ZipEntry ze;
int count;
byte[] buffer = new byte[8192];
while ((ze = zis.getNextEntry()) != null) {
File file = new File(targetDirectory, ze.getName());
File dir = ze.isDirectory() ? file : file.getParentFile();
if (!dir.isDirectory() && !dir.mkdirs())
throw new FileNotFoundException("Failed to ensure directory: " +
dir.getAbsolutePath());
if (ze.isDirectory())
continue;
FileOutputStream fout = new FileOutputStream(file);
try {
while ((count = zis.read(buffer)) != -1)
fout.write(buffer, 0, count);
} finally {
fout.close();
}
/* if time should be restored as well
long time = ze.getTime();
if (time > 0)
file.setLastModified(time);
*/
}
} finally {
zis.close();
}
}
显著差异
public static
- 这是一个静态的实用程序方法,可以在任何地方。File
String
path + filename
throws
- 因为捕获晚 - 如果真的对它们不感兴趣,请添加一个尝试捕获。mkdirs()
finally
所以
unzip(new File("/sdcard/pictures.zip"), new File("/sdcard"));
应该做相当于原来的
unpackZip("/sdcard/", "pictures.zip")