{"id":5252,"date":"2022-05-12T20:39:08","date_gmt":"2022-05-12T12:39:08","guid":{"rendered":"https:\/\/ixyzero.com\/blog\/?p=5252"},"modified":"2022-05-12T20:39:08","modified_gmt":"2022-05-12T12:39:08","slug":"java%e4%b8%adzip%e6%96%87%e4%bb%b6%e7%9a%84%e5%8e%8b%e7%bc%a9%e5%92%8c%e8%a7%a3%e5%8e%8b%e7%bc%a9","status":"publish","type":"post","link":"https:\/\/ixyzero.com\/blog\/archives\/5252.html","title":{"rendered":"Java\u4e2dzip\u6587\u4ef6\u7684\u538b\u7f29\u548c\u89e3\u538b\u7f29"},"content":{"rendered":"\n<p>=Start=<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">\u7f18\u7531\uff1a<\/h4>\n\n\n\n<p>\u7b80\u5355\u8bb0\u5f55\u4e00\u4e0b\u5982\u4f55\u7528Java\u5bf9zip\u6587\u4ef6\u8fdb\u884c\u538b\u7f29\u548c\u89e3\u538b\u7f29\uff0c\u5c24\u5176\u662f\u5982\u4f55\u5c06\u7279\u5b9a\u6587\u4ef6\u6dfb\u52a0\u5230\u4e00\u4e2a\u5df2\u6709\u7684zip\u538b\u7f29\u5305\u4e2d\uff08\u4e0d\u7528\u5148\u89e3\u538b\uff0c\u590d\u5236\uff0c\u7136\u540e\u91cd\u538b\u7f29\u7684\u65b9\u5f0f\u5b9e\u73b0\uff09\u3002<\/p>\n\n\n\n<h4 class=\"wp-block-heading\">\u6b63\u6587\uff1a<\/h4>\n\n\n\n<h5 class=\"wp-block-heading\">\u53c2\u8003\u89e3\u7b54\uff1a<\/h5>\n\n\n\n<p>\u538b\u7f29\u548c\u89e3\u538b\u7f29\u7279\u5b9a\u6587\u4ef6\u7684\u4ee3\u7801\u57fa\u672c\u662f\u4ece Baeldung \u8fd9\u91cc\u62f7\u8d1d\u8fc7\u6765\u7684\uff0c\u76f4\u63a5\u5f80\u5df2\u6709zip\u538b\u7f29\u5305\u4e2d\u6dfb\u52a0\u6587\u4ef6\u662f\u4ece\u5b98\u7f51\u4e2d\u7684\u793a\u4f8b\u4e2d\u6539\u7684\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>package com.example;\n\nimport java.io.*;\nimport java.nio.file.FileSystem;\nimport java.nio.file.*;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipInputStream;\nimport java.util.zip.ZipOutputStream;\n\n\/**\n * @author ixyzero\n * Created on 2022-05-09\n *\/\npublic class opZip {\n    public static void main(String&#91;] args) {\n        String sourceFile = \"new-test-docx.docx\";\n        String zipFile = \"test-output.zip\";\n        String appendFile = \"new-test-xlsx.xlsx\";\n        String appendFile2 = \"new-test-xlsx.rar\";\n        String unzipDir = \"unzipTest\";\n\n        try {\n            FileOutputStream fos = new FileOutputStream(zipFile);\n            ZipOutputStream zipOut = new ZipOutputStream(fos);\n\n            File fileToZip = new File(sourceFile);\n            zipFile(fileToZip, fileToZip.getName(), zipOut);\n\n            zipOut.close();\n            fos.close();\n            System.out.println(\"zip file success!\");\n\n            addFileToZip(appendFile, zipFile);\n            addFileToZip2(appendFile2, zipFile);\n\n            unzipFile(zipFile, unzipDir);\n        } catch (FileNotFoundException e) {\n            e.printStackTrace();\n        } catch (IOException e) {\n            e.printStackTrace();\n        } catch (Exception e) {\n            e.printStackTrace();\n        }\n    }\n\n    \/\/ https:\/\/www.baeldung.com\/java-compress-and-uncompress\n    private static void unzipFile(String filePath, String unzipDir) throws Exception {\n        File zipFile = new File(filePath);\n        File destDir = new File(unzipDir);\n        byte&#91;] buffer = new byte&#91;1024];\n        ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));\n        ZipEntry zipEntry = zis.getNextEntry();\n        while (zipEntry != null) {\n            File newFile = newFile(destDir, zipEntry);\n            if (zipEntry.isDirectory()) {\n                if (!newFile.isDirectory() &amp;&amp; !newFile.mkdirs()) {\n                    throw new IOException(\"Failed to create directory \" + newFile);\n                }\n            } else {\n                \/\/ fix for Windows-created archives\n                File parent = newFile.getParentFile();\n                if (!parent.isDirectory() &amp;&amp; !parent.mkdirs()) {\n                    throw new IOException(\"Failed to create directory \" + parent);\n                }\n\n                \/\/ write file content\n                FileOutputStream fos = new FileOutputStream(newFile);\n                int len;\n                while ((len = zis.read(buffer)) &gt; 0) {\n                    fos.write(buffer, 0, len);\n                }\n                fos.close();\n            }\n            zipEntry = zis.getNextEntry();\n        }\n        zis.closeEntry();\n        zis.close();\n        System.out.println(\"unzip file success!\");\n    }\n\n    private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut) throws IOException {\n        if (fileToZip.isHidden()) {\n            return;\n        }\n        if (fileToZip.isDirectory()) {\n            if (fileName.endsWith(\"\/\")) {\n                zipOut.putNextEntry(new ZipEntry(fileName));\n                zipOut.closeEntry();\n            } else {\n                zipOut.putNextEntry(new ZipEntry(fileName + \"\/\"));\n                zipOut.closeEntry();\n            }\n            File&#91;] children = fileToZip.listFiles();\n            for (File childFile : children) {\n                zipFile(childFile, fileName + \"\/\" + childFile.getName(), zipOut);\n            }\n            return;\n        }\n        FileInputStream fis = new FileInputStream(fileToZip);\n        ZipEntry zipEntry = new ZipEntry(fileName);\n        zipOut.putNextEntry(zipEntry);\n        byte&#91;] bytes = new byte&#91;1024];\n        int length;\n        while ((length = fis.read(bytes)) &gt;= 0) {\n            zipOut.write(bytes, 0, length);\n        }\n        fis.close();\n    }\n\n    public static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException {\n        File destFile = new File(destinationDir, zipEntry.getName());\n\n        String destDirPath = destinationDir.getCanonicalPath();\n        String destFilePath = destFile.getCanonicalPath();\n\n        if (!destFilePath.startsWith(destDirPath + File.separator)) {\n            throw new IOException(\"Entry is outside of the target dir: \" + zipEntry.getName());\n        }\n\n        return destFile;\n    }\n\n    \/\/ work well, but only can add file not directory(files under dir can not be added)\n    \/\/ https:\/\/stackoverflow.com\/questions\/13787318\/java-util-zip-replace-a-single-zip-file\n    public static void addFileToZip(String filePathStr, String zipFilePathStr) throws Exception {\n        Path myFilePath = Paths.get(filePathStr);\n        Path zipFilePath = Paths.get(zipFilePathStr);\n        try( FileSystem fs = FileSystems.newFileSystem(zipFilePath, null) ) {\n            Path fileInsideZipPath = fs.getPath(filePathStr.contains(\"\/\") ?\n                    filePathStr.substring(filePathStr.lastIndexOf(\"\/\")) : \"\/\"+filePathStr);\n            Files.copy(myFilePath, fileInsideZipPath); \/\/ fileInsideZipPath \u5b57\u7b26\u4e32\u7684\u5185\u5bb9\u5176\u5b9e\u53ef\u4ee5\u4efb\u610f\u8bbe\u7f6e\n        } catch (IOException e) {\n            \/\/ TODO Auto-generated catch block\n            e.printStackTrace();\n        }\n        return;\n    }\n\n    \/\/ do not work, until add fs.close()\n    public static void addFileToZip2(String filePathStr, String zipFilePathStr) throws Exception {\n        Path myFilePath = Paths.get(filePathStr);\n        Path zipFilePath = Paths.get(zipFilePathStr);\n        FileSystem fs = FileSystems.newFileSystem(zipFilePath, null);\n        Path fileInsideZipPath = fs.getPath(filePathStr.contains(\"\/\") ?\n                filePathStr.substring(filePathStr.lastIndexOf(\"\/\")) : \"\/\"+filePathStr);\n        Files.copy(myFilePath, fileInsideZipPath);\n        fs.close(); \/\/ don't forget to add this after modify try-with-resources statement\n        return;\n    }\n\n}<\/code><\/pre>\n\n\n\n<p>JDK7\u4e4b\u540e\uff0cJava\u591a\u4e86\u4e2a\u65b0\u7684\u8bed\u6cd5\uff1atry-with-resources\u8bed\u53e5\uff0c\u53ef\u4ee5\u7406\u89e3\u4e3a\u662f\u4e00\u4e2a\u58f0\u660e\u4e00\u4e2a\u6216\u591a\u4e2a\u8d44\u6e90\u7684 try\u8bed\u53e5\uff08\u7528\u5206\u53f7\u9694\u5f00\uff09\uff0c\u4e00\u4e2a\u8d44\u6e90\u4f5c\u4e3a\u4e00\u4e2a\u5bf9\u8c61\uff0c\u5e76\u4e14\u8fd9\u4e2a\u8d44\u6e90\u5fc5\u987b\u8981\u5728\u6267\u884c\u5b8c\u5173\u95ed\u7684\uff0c<strong>try-with-resources\u8bed\u53e5\u786e\u4fdd\u5728\u8bed\u53e5\u6267\u884c\u5b8c\u6bd5\u540e\uff0c\u6bcf\u4e2a\u8d44\u6e90\u90fd\u88ab\u81ea\u52a8\u5173\u95ed \u3002<\/strong><\/p>\n\n\n\n<h5 class=\"wp-block-heading\">\u53c2\u8003\u94fe\u63a5\uff1a<\/h5>\n\n\n\n<p>Zipping and Unzipping in Java<br><a href=\"https:\/\/www.baeldung.com\/java-compress-and-uncompress\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.baeldung.com\/java-compress-and-uncompress<\/a><\/p>\n\n\n\n<p>How to create Zip file in Java<br><a href=\"https:\/\/mkyong.com\/java\/how-to-compress-files-in-zip-format\/\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/mkyong.com\/java\/how-to-compress-files-in-zip-format\/<\/a><\/p>\n\n\n\n<p>Package java.util.zip<br><a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/util\/zip\/package-summary.html\">https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/util\/zip\/package-summary.html<\/a><\/p>\n\n\n\n<p>Copying a File or Directory<br><a href=\"https:\/\/docs.oracle.com\/javase\/tutorial\/essential\/io\/copy.html\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/docs.oracle.com\/javase\/tutorial\/essential\/io\/copy.html<\/a><\/p>\n\n\n\n<p>The try-with-resources Statement<br><a href=\"https:\/\/docs.oracle.com\/javase\/tutorial\/essential\/exceptions\/tryResourceClose.html\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/docs.oracle.com\/javase\/tutorial\/essential\/exceptions\/tryResourceClose.html<\/a><\/p>\n\n\n\n<p>Java \u2013 Try with Resources<br><a href=\"https:\/\/www.baeldung.com\/java-try-with-resources\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.baeldung.com\/java-try-with-resources<\/a><\/p>\n\n\n\n<p>The try-with-resources statement<br><a href=\"https:\/\/www.javatpoint.com\/java-try-with-resources\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.javatpoint.com\/java-try-with-resources<\/a><\/p>\n\n\n\n<p>java try-with-resource\u8bed\u53e5\u4f7f\u7528<br><a href=\"https:\/\/www.jianshu.com\/p\/258c5ce1a2bd\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/www.jianshu.com\/p\/258c5ce1a2bd<\/a><\/p>\n\n\n\n<p>\u6df1\u5165\u7406\u89e3 Java try-with-resource \u8bed\u6cd5\u7cd6<br><a href=\"https:\/\/juejin.cn\/post\/6844903446185951240\" target=\"_blank\" rel=\"noreferrer noopener\">https:\/\/juejin.cn\/post\/6844903446185951240<\/a><\/p>\n\n\n\n<p>=END=<\/p>\n","protected":false},"excerpt":{"rendered":"<p>=Start= \u7f18\u7531\uff1a \u7b80\u5355\u8bb0\u5f55\u4e00\u4e0b\u5982\u4f55\u7528Java\u5bf9zip\u6587\u4ef6\u8fdb\u884c\u538b\u7f29\u548c\u89e3\u538b\u7f29\uff0c\u5c24\u5176\u662f\u5982\u4f55\u5c06\u7279\u5b9a\u6587\u4ef6\u6dfb\u52a0\u5230\u4e00\u4e2a [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[23,7,12],"tags":[1812,61,1811,1810],"class_list":["post-5252","post","type-post","status-publish","format-standard","hentry","category-knowledgebase-2","category-programing","category-tools","tag-files-copy","tag-java","tag-try-with-resources","tag-zip"],"views":1492,"_links":{"self":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/5252","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/comments?post=5252"}],"version-history":[{"count":2,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/5252\/revisions"}],"predecessor-version":[{"id":5254,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/posts\/5252\/revisions\/5254"}],"wp:attachment":[{"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/media?parent=5252"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/categories?post=5252"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/ixyzero.com\/blog\/wp-json\/wp\/v2\/tags?post=5252"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}