Java:解压缩文件,而不创建目标文件夹
我有一个很好的java代码,可以解压.zip文件。但这个代码的问题是Java:解压缩文件,而不创建目标文件夹,java,android,unzip,Java,Android,Unzip,我有一个很好的java代码,可以解压.zip文件。但这个代码的问题是 在运行此代码之前,我需要创建目标文件夹(注意:只有文件夹而不是文件) 否则我将获取路径未找到异常 因此,如果以前不知道zip文件内容,则此代码将无法工作。所以我认为这是无用的代码。谁有更好的逻辑?或者下面的代码需要编辑 package com.mireader; import android.os.Environment; import android.util.Log; import java.io.File; impo
package com.mireader;
import android.os.Environment;
import android.util.Log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
*
* @author jon
*/
public class Decompress {
private String _zipFile;
private String _location;
public Decompress(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
byte[] buffer = new byte[1024];
int length;
int i=0;
while ((ze = zin.getNextEntry()) != null) {
Log.v("t", ze.toString());
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
Log.i("my","Comes to if");
_dirChecker(ze.getName());
}
else {
Log.i("my","Comes to else");
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
while ((length = zin.read(buffer))>0) {
fout.write(buffer, 0, length);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
Log.i("My tag","Success");
}catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
Log.i("mytag", "Creating new folder");
f.mkdirs();
System.out.print("stp:"+f.getName());
}
}
}
看起来没什么问题,你到底有什么问题? 创建zip文件中显示的目录;我通常是内联的,但都是一样的。如果zip文件中没有目录存根(这可能发生在野外的zip创建者身上),那么您的代码将失败,因此我的解压代码在提取每个文件之前会双重检查目录的存在性:
if (zEntry.isDirectory()) new File(destDir+zEntry.getName()).mkdirs();
else
{
String dstEntryDir=new File(destDir+zEntry.getName()).getParent()+File.separator;
if (!fileExists(dstEntryDir)) new File(dstEntryDir).mkdirs();
copyStreamToFile(zFile.getInputStream(zEntry),destDir+zEntry.getName());
}
您可以避免以下代码
if(ze.isDirectory()) {
Log.i("my","Comes to if");
_dirChecker(ze.getName());
}
并在file creator else部分添加与下面类似的代码。它通过创建整个父文件夹对我有效
File file = createFile((baseDirectory +"/" + zipFile.getName()));
file.getParentFile().mkdirs();
你试过你的代码了吗?这不是他的代码——快速的谷歌搜索揭示了这一点:也许他应该编写自己的代码,或者开发知道一段代码是否达到预期效果的能力。看来他两样都不行!fileExists()和copyStreamToFile()的作用应该是明确的,因此不包括在内。