android zip解压文件
解压代码如下代码如下:
public static void unZipFile(String zipPath,String unZipPath) throws ZipException,IOException
{
File dirFile = new File(unZipPath);
if(!dirFile.exists())
{
dirFile.mkdirs();
}
ZipFile zipFile = new ZipFile(zipPath);
InputStream input = null;
OutputStream output = null;
try
{
Enumeration<?> entries = zipFile.entries();
while(entries.hasMoreElements())
{
ZipEntry zipEntry = (ZipEntry)entries.nextElement();
if(zipEntry.isDirectory())
{
String nameString = zipEntry.getName();
nameString = nameString.substring(0,nameString.length()-1);
File file = new File(unZipPath);
file.mkdirs();
}
else
{
String filePath = unZipPath+File.separator+zipEntry.getName();
filePath = new String(filePath.getBytes(),"gbk");
File file = new File(filepath);
file.getParentFile().mkdirs();
file.createNewFile();
input = zipFile.getInputStream(zipEntry);
output = new FileOutputStream(file);
byte[] buffer = new byte[BUFFER_SIZE];
int realLength = 0;
while((realLength = input.read(buffer)) != -1)
{
output.write(buffer,0,realLength);
}
}
}
zipFile.close();
}
finally
{
if(input != null)
{
input.close();
}
if(output != null)
{
output.flush();
output.close();
}
}
}
需要解压的文件的路径:
String SDPATH= Environment.getExternalStorageDirectory() +"/";
String fromPath = SDPATH+"ABC/"+"abc.zip";
String toPath = SDPATH+"ABC";
unZipFile(fromPath,toPath);
上面那段解压的代码解压本地电脑上的文件时可以的,但是android上面是不可以的,不知道怎么回事?
[解决办法]
public static boolean unZip(String zipDirectory, String storageDirectory,
String fileName) {
boolean result = false;
String zipName = zipDirectory + fileName;
String filePath = storageDirectory;
ZipFile zipFile = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
zipFile = new ZipFile(zipName);
Enumeration<? extends ZipEntry> emu = zipFile.entries();
while (emu.hasMoreElements()) {
ZipEntry entry = (ZipEntry) emu.nextElement();
if (entry.isDirectory()) {
new File(filePath + entry.getName()).mkdirs();
continue;
}
bis = new BufferedInputStream(zipFile.getInputStream(entry));
File file = new File(filePath + entry.getName());
File parent = file.getParentFile();
if (parent != null && (!parent.exists())) {
parent.mkdirs();
}
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, BUFFER);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
}
result = true;
}
catch (Exception e) {
e.printStackTrace();
result = false;
}
finally {
try {
if (null != bos) {
bos.close();
}
if (null != bis) {
bis.close();
}
if (null != zipFile) {
zipFile.close();
}
}
catch (IOException e) {
e.printStackTrace();
result = false;
}
}
return result;
}
原来写过的一个解压方法,可以正常解压。
zipDirectory 是压缩文件路径
storageDirectory 是解压文件路径
fileName 是压缩文件名(xxx.zip)
------解决方案--------------------
呵呵, 最近也在搞这个东西
LZ 可以借鉴一下如下博文
http://blog.csdn.net/spjhandsomeman/article/details/8140182
希望有所帮助
