我已经完成了某种实现,当我创建 zip 文件时一切都很好,创建了 zip 文件并且它还包含所有文件而不创建目录结构。这意味着当我解压缩文件时,我看到了所有没有目录结构的文件。请帮我整理一下。。
这是我写的代码..
public void createZipFolder(String path)
{
File dir = new File(path);
String list[] = dir.list();
String name = path.substring(path.lastIndexOf("/"), path.length());
String n = path.substring(path.indexOf("/"), path.lastIndexOf("/"));
Log.d("JWP", "New Path :"+n);
String newPath;
if(!dir.canRead() || !dir.canWrite()){
return;
}
int len = list.length;
if(path.charAt(path.length() - 1) != '/'){
newPath = n + "/";
}
else{
newPath = n;
}
try{
ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newPath + name + ".zip"),BUFFER));
for(int i = 0; i < len; i++){
zip_Folder(new File(path +"/"+ list[i]),zipOut);
}
zipOut.close();
}
catch(FileNotFoundException e){
Log.e("File Not Found", e.getMessage());
}
catch(IOException e){
Log.e("IOException", e.getMessage());
}
}
private void zip_Folder(File file, ZipOutputStream zipOut)throws IOException {
// TODO Auto-generated method stub
String s1 = file.getPath();
Log.d("JWP", "PATH "+s1);
byte data[] = new byte[BUFFER];
int read;
if(file.isFile()){
ZipEntry entry = new ZipEntry(file.getName());
zipOut.putNextEntry(entry);
BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(file));
while((read = inputStream.read(data,0,BUFFER)) != -1){
zipOut.write(data, 0, read);
}
zipOut.closeEntry();
inputStream.close();
}
else if(file.isDirectory()){
String[] list = file.list();
int len = list.length;
for(int i = 0; i < len; i++)
zip_Folder(new File(file.getPath()+"/"+ list[i]), zipOut);
}
}
这是解压缩的代码...
public void extractZipFiles(String zipFile, String dir){
Log.d("JWP", "ZIP FILE :"+zipFile+ " DIR :"+dir);
byte data[] = new byte[BUFFER];
String name,path,zipDir;
ZipEntry entry;
ZipInputStream zipInputStream;
if(!(dir.charAt(dir.length() - 1) == '/' )){
dir += "/";
}
if(zipFile.contains("/")){
path = zipFile;
name = path.substring(path.lastIndexOf("/") + 1, path.length() - 4);
zipDir = dir + name + "/";
}
else{
path = dir + zipFile;
name = path.substring(path.lastIndexOf("/") + 1, path.length() - 4);
zipDir = dir + name + "/";
}
new File(zipDir).mkdir();
try{
zipInputStream = new ZipInputStream(new FileInputStream(path));
while((entry = zipInputStream.getNextEntry()) != null){
String buildDir = zipDir;
String dirs[] = entry.getName().split("/");
if(dirs != null && dirs.length > 0){
for(int i = 0; i < dirs.length - 1; i++){
buildDir += dirs[i] + "/";
new File(buildDir).mkdir();
}
}
int read = 0;
FileOutputStream out = new FileOutputStream(zipDir + entry.getName());
while((read = zipInputStream.read(data, 0, BUFFER)) != -1){
out.write(data, 0, read);
}
zipInputStream.closeEntry();
out.close();
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
}