`

JAVA解压缩文件——包含嵌套的压缩文件

    博客分类:
  • java
阅读更多
今天主要介绍JAVA处理ZIP文件,JAVA提供了相应的类、方法来处理ZIP的压缩文件:

public static boolean zipToFile(String sZipPathFile, String sDestPath) {   
        boolean flag = false;   
        try {   
           FileInputStream fins = new FileInputStream(sZipPathFile);   
           ZipInputStream zins = new ZipInputStream(fins);   
           ZipEntry ze = null;   
           byte ch[] = new byte[256];   
           while ((ze = zins.getNextEntry()) != null) {   
        	   File zfile = new File(sDestPath + "//" + ze.getName());  
               File fpath = new File(zfile.getParentFile().getPath());   
               if (ze.isDirectory()) {   
                    if (!zfile.exists())   
                        zfile.mkdirs();   
                    zins.closeEntry();   
                } else {   
                    if (!fpath.exists())   
                        fpath.mkdirs();   
                    FileOutputStream fouts = new FileOutputStream(zfile);   
                    int i;   
                   String zfilePath = zfile.getAbsolutePath();   
                    while ((i = zins.read(ch)) != -1)   
                        fouts.write(ch, 0, i);   
                   zins.closeEntry();   
                    fouts.close();   
  
                    if (zfilePath.endsWith(".zip")) {   
                       zipToFile(zfilePath, zfilePath.substring(0, zfilePath   
                                .lastIndexOf(".zip")));
                       zfile.delete();
                   }   
 
                }   
            }   
           fins.close();   
           zins.close();   
           // if necessary, delete original zip-file   
//           File file = new File(sZipPathFile);   
//           file.delete();   
           flag = true;   
        } catch (Exception e) {   
            System.err.println("Extract error:" + e.getMessage());   
        }   
        return flag;   
    }


此解压方法支持压缩文件里面嵌套压缩文件(zip格式的压缩文件)

递归获得文件夹下面所有的文件:

public static List<Map> getAllFile(String path)
	{
		if(path.indexOf(".zip")>0)
		{
			zipToFile(path,tempPath);
			getAllFile(tempPath);
		}else{
			File dir = new File(path);
			File[] files = dir.listFiles(); 
			if (files == null) 
			{
				return null; 
			}
			for (int i = 0; i < files.length; i++) { 
				Map map = new HashMap();
				if (files[i].isDirectory()) { 
					getAllFile(files[i].getAbsolutePath()); 
				} else { 
					String filename = files[i].getName();
					if(filename.indexOf(".zip")>0)
					{
						zipToFile(files[i].getAbsolutePath(),tempPath+"\\tempfile_"+i);
						getAllFile(tempPath+"\\tempfile_"+i);
					}else{
						map.put("filepath", files[i].getAbsolutePath());
						map.put("filename", files[i].getName());
						filelist.add(map); 
					}
				} 
			}
		}
		return filelist;
	}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics