解决java.util.zip.ZipFile解压含中文内容的压缩包报:MALFORMED的问题

    xiaoxiao2023-10-09  179

    报这个错误是因为压缩包的编码格式问题造成的,网络上的文章普遍都是说对压缩包做下转码处理。代码如下: ZipFile sourceZip = new ZipFile(“D://A.zip”,Charset.forName(“GB2312”)); zipFile是使用的java.util包中的。JDK自带的工具类。 但是不同的操作系统中文的编码格式是不一样的。需根据实际场景做下处理。 第二种方法是使用apache的commons-compress包提供的方法,具体代码如下: 引入包: org.apache.commons commons-compress 1.8.1 我写的是一个压缩包的复制操作,在window10的系统里面能执行成功,其他的操作系统没有验证了:

    public static void main(String[] args) { ZipFile sourceZip = null; ZipOutputStream targetZip = null; FileOutputStream outputStream = null; String path = “D://B.zip”; try { sourceZip = new ZipFile(“D://A.zip”); outputStream = new FileOutputStream(new File(path)); targetZip = new ZipOutputStream(outputStream); Enumeration<? extends ZipArchiveEntry> entries = sourceZip.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); System.out.println(entry.getName()); if (!entry.isDirectory()) { targetZip.putNextEntry(new ZipEntry(entry.getName())); copy(sourceZip.getInputStream(entry), targetZip); targetZip.closeEntry(); } } } catch (Exception e) { System.out.println("-----"+e); } finally { try { sourceZip.close(); } catch (Exception e2) {} try { targetZip.close(); } catch (Exception e2) {} try { outputStream.close(); } catch (Exception e2) {} } } private static final byte[] BUFFER = new byte[4096 * 1024]; public static void copy(InputStream input, OutputStream output) throws IOException { int bytesRead; while ((bytesRead = input.read(BUFFER)) != -1) { output.write(BUFFER, 0, bytesRead); } }

    最新回复(0)