# 压缩流 已知 ZipOutputStream 是 Java 标准库的压缩输出流,那么下列哪个选项可以正确的将指定文件压缩为zip文件? ## 答案 ```java String sourceFile = "path_to_source"; File fileToZip = new File(sourceFile); try (FileOutputStream fos = new FileOutputStream("path_to_zip"); FileInputStream fis = new FileInputStream(fileToZip); ZipOutputStream zipOut = new ZipOutputStream(fos);) { ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } } ``` ## 选项 ### 没有关闭资源 ```java String sourceFile = "path_to_source"; File fileToZip = new File(sourceFile); FileOutputStream fos = new FileOutputStream("path_to_zip"); FileInputStream fis = new FileInputStream(fileToZip); ZipOutputStream zipOut = new ZipOutputStream(fos); ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } ``` ### ZipOutputStream 不能直接读写文件,需要接入其它字节流 ```java String sourceFile = "path_to_source"; File fileToZip = new File(sourceFile); try (FileInputStream fis = new FileInputStream(fileToZip); ZipOutputStream zipOut = new ZipOutputStream("path_to_zip");) { ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } } ``` ### 缓冲区需要初始化 ```java String sourceFile = "path_to_source"; File fileToZip = new File(sourceFile); try (FileOutputStream fos = new FileOutputStream("path_to_zip"); FileInputStream fis = new FileInputStream(fileToZip); ZipOutputStream zipOut = new ZipOutputStream(fos);) { ZipEntry zipEntry = new ZipEntry(fileToZip.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = null; int length; while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } } ```