Java 对zip汉语件基于大小的对比处理
Java 对zip中文件基于大小的对比处理
zip文件可以通过ZipFile类得到初始化时传入文件名filename new ZipFile(filename );
获得zip文件后可以根据每个子文件大小和子文件的名字构建map,传入ZipFile.entries()到下面方法可构建
private static Map<String, Long> getZipEntriesSizeMap( Enumeration<? extends ZipEntry> entries) { Map<String, Long> fileMap = new HashMap<String, Long>(); while (entries.hasMoreElements()) { ZipEntry first = entries.nextElement(); fileMap.put(first.getName(), first.getSize()); } return fileMap; }
获得map后可以根据两个map中的key进行对比value值
Iterator<String> ite = firstMap.keySet().iterator(); while (ite.hasNext()) { String fileName = ite.next(); if (secondMap.containsKey(fileName)) { if (firstMap.get(fileName).equals(secondMap.get(fileName))) { // when the file in first zip and second zip is same i // remove it secondMap.remove(fileName); } else { // 添加到一个定义的输出列中 } }
对比时应对比两次 即第一个zip包生成的map和第二个比对后,应把第二个和第一个再次比对,因为双方都有可能有对方所没有的文件
而对于子文件是jar文件或者zip文件时也可以进行比较代码如下
if (file.getName().lastIndexOf(".jar") != -1 || file.getName().lastIndexOf(".zip") != -1) { InputStream in = zipfile.getInputStream(file); temp = File.createTempFile("leotemp", ".tmp"); temp.deleteOnExit(); BufferedOutputStream out = new BufferedOutputStream( new FileOutputStream(temp)); byte[] buffer = new byte[2048]; int nBytes = 0; while ((nBytes = in.read(buffer)) > 0) { out.write(buffer, 0, nBytes); } out.close(); ZipFile subzip = new ZipFile(temp); subzip.entries(); if(parentPath != null && parentPath.trim() != ""){ fileMap.putAll(getZipEntriesSizeMap(subzip ,parentPath+" : "+file.getName())); }else{ fileMap.putAll(getZipEntriesSizeMap(subzip ,file.getName())); } temp.delete(); }
parentPath为父文件的路径名字,第一传入时可以为空或者""
一般我会输出为一个xml文件,xml文件利用dom4j的jar包很容易创建并实现值得注意的只有一点,工具制作成jar包运行时,内部的路径应为相对路径即首字符应为"/包名/文件名"形式才能被访问到