Java-工具类之ZIP压缩解压
生活随笔
收集整理的這篇文章主要介紹了
Java-工具类之ZIP压缩解压
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
- 概述
- 實例
- zip壓縮單個或者多個文件
- unzip到指定目錄
- zip目錄及子孫目錄
- 不解壓讀取zip中的文件列表
概述
整理ZIP相關的工具類
實例
代碼已托管到 https://github.com/yangshangwei/commonUtils
zip壓縮單個或者多個文件
package com.artisan.commonUtils.zip;import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;/*** * * @ClassName: ZipUtility* * @Description: 【Steps to Compress a File in Java 】* * Here are the steps to compress a file using Java code:* * 1. Open a ZipOutputStream that wraps an OutputStream like* FileOutputStream. The ZipOutputStream class implements an* output stream filter for writing in the ZIP file format.* * 2. Put a ZipEntry object by calling the putNextEntry(ZipEntry)* method on the ZipOutputStream. The ZipEntry class represents an* entry of a compressed file in the ZIP file.* * 3. Read all bytes from the original file by using the* Files.readAllBytes(Path) method.* * 4. Write all bytes read to the output stream using the* write(byte[] bytes, int offset, int length) method.* * 5. Close the ZipEntry.* * 6. Close the ZipOutputStream.* * You can also set the compression method and compression level* using the following ZipOutputStream’s methods:* * A: setMethod(int method): there are 2 methods: DEFLATED (the* default) which compresses the data; and STORED which doesn’t* compress the data (archive only).* * B: setLevel(int level): sets the compression level ranging from* 0 to 9 (the default).* * @author: Mr.Yang* * @date: 2017年9月7日 下午8:24:15*/ public class ZipUtility {/*** * * @Title: compressSingleFile* * @Description: compress a file in ZIP format* * @param filePath* * @return: void*/public static void compressSingleFile(String filePath, String outPut) {try {File file = new File(filePath);String zipFileName = file.getName().concat(".zip");System.out.println("zipFileName:" + zipFileName);// if you want change the menu of output ,just fix here// FileOutputStream fos = new FileOutputStream(zipFileName);FileOutputStream fos = new FileOutputStream(outPut + File.separator + zipFileName);ZipOutputStream zos = new ZipOutputStream(fos);zos.putNextEntry(new ZipEntry(file.getName()));byte[] bytes = Files.readAllBytes(Paths.get(filePath));zos.write(bytes, 0, bytes.length);zos.closeEntry();zos.close();} catch (FileNotFoundException ex) {System.err.format("The file %s does not exist", filePath);} catch (IOException ex) {System.err.println("I/O error: " + ex);}}/*** * * @Title: compressMultipleFiles* * @Description: compresses multiple files into a single ZIP file.* * The file paths are passed from the command line,* * and the ZIP file name is name of the first file followed by* the .zip extension* * @param filePaths* * @return: void*/public static void compressMultipleFiles(String... filePaths) {try {File firstFile = new File(filePaths[0]);String zipFileName = firstFile.getName().concat(".zip");FileOutputStream fos = new FileOutputStream(zipFileName);ZipOutputStream zos = new ZipOutputStream(fos);for (String aFile : filePaths) {zos.putNextEntry(new ZipEntry(new File(aFile).getName()));byte[] bytes = Files.readAllBytes(Paths.get(aFile));zos.write(bytes, 0, bytes.length);zos.closeEntry();}zos.close();} catch (FileNotFoundException ex) {System.err.println("A file does not exist: " + ex);} catch (IOException ex) {System.err.println("I/O error: " + ex);}}public static void main(String[] args) {ZipUtility.compressSingleFile("D:/JavaMaster.log", "H:");ZipUtility.compressMultipleFiles("D:/Temp.log", "D:/JavaMaster.log");}}unzip到指定目錄
package com.artisan.commonUtils.zip;import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream;/*** * * @ClassName: UnzipUtility* * @Description: The java.util.zip package provides the following classes for* extracting files and directories from a ZIP archive:* * A:----> ZipInputStream: this is the main class which can be* used for reading zip file and extracting files and directories* (entries) within the archive. Here are some important usages of* this class:* * 1.read a zip via its constructor* ZipInputStream(FileInputStream)* * 2.read entries of files and directories via method* getNextEntry()* * 3.read binary data of current entry via method read(byte)* * 4.close current entry via method closeEntry()* * 5.close the zip file via method close()* * * * B:----> ZipEntry: this class represents an entry in the zip* file. Each file or directory is represented as a ZipEntry* object. Its method getName() returns a String which represents* path of the file/directory.* * The path is in the following form:* folder_1/subfolder_1/subfolder_2/…/subfolder_n/file.ext* * @author: Mr.Yang* * @date: 2017年9月7日 下午8:10:06* * * @comments The UnzipUtility class has a public method for extracting files and* directories from a zip archive:* * unzip(String zipFilePath, String destDirectory):* * extracts content of a zip file specified by zipFilePath to a* directory specified by destDirectory.* */ public class UnzipUtility {/*** Size of the buffer to read/write data*/private static final int BUFFER_SIZE = 4096;/*** Extracts a zip file specified by the zipFilePath to a directory specified* by destDirectory (will be created if does not exists)* * @param zipFilePath* @param destDirectory* @throws IOException*/public static void unzip(String zipFilePath, String destDirectory) throws IOException {File destDir = new File(destDirectory);if (!destDir.exists()) {destDir.mkdir();}ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFilePath));ZipEntry entry = zipIn.getNextEntry();// iterates over entries in the zip filewhile (entry != null) {String filePath = destDirectory + File.separator + entry.getName();if (!entry.isDirectory()) {// if the entry is a file, extracts itextractFile(zipIn, filePath);} else {// if the entry is a directory, make the directoryFile dir = new File(filePath);dir.mkdir();}zipIn.closeEntry();entry = zipIn.getNextEntry();}zipIn.close();}/*** Extracts a zip entry (file entry)* * @param zipIn* @param filePath* @throws IOException*/public static void extractFile(ZipInputStream zipIn, String filePath) throws IOException {BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));byte[] bytesIn = new byte[BUFFER_SIZE];int read = 0;while ((read = zipIn.read(bytesIn)) != -1) {bos.write(bytesIn, 0, read);}bos.close();}public static void main(String[] args) {String zipFilePath = "D:/test.zip";String destDirectory = "H:/";try {UnzipUtility.unzip(zipFilePath, destDirectory);} catch (Exception ex) {ex.printStackTrace();}}}zip目錄及子孫目錄
package com.artisan.commonUtils.zip;import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;/*** * * @ClassName: ZipWholeDirAndSubsDir* * @Description: Using the walk file tree feature of Java NIO,* * you can write a program that compresses a whole directory* (including sub files and sub directories) with ease* * @author: Mr.Yang* * @date: 2017年9月7日 下午8:36:18*/ public class ZipWholeDirAndSubsDir extends SimpleFileVisitor<Path> {private static ZipOutputStream zos;private Path sourceDir;public ZipWholeDirAndSubsDir(Path sourceDir) {this.sourceDir = sourceDir;}@Overridepublic FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {try {Path targetFile = sourceDir.relativize(file);zos.putNextEntry(new ZipEntry(targetFile.toString()));byte[] bytes = Files.readAllBytes(file);zos.write(bytes, 0, bytes.length);zos.closeEntry();} catch (IOException ex) {System.err.println(ex);}return FileVisitResult.CONTINUE;}public static void main(String[] args) {String dirPath = "H:/Sessions";Path sourceDir = Paths.get(dirPath);try {String zipFileName = dirPath.concat(".zip");zos = new ZipOutputStream(new FileOutputStream(zipFileName));Files.walkFileTree(sourceDir, new ZipWholeDirAndSubsDir(sourceDir));zos.close();} catch (IOException ex) {System.err.println("I/O Error: " + ex);}}}不解壓讀取zip中的文件列表
package com.artisan.commonUtils.zip;import java.io.IOException; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile;/*** * * @ClassName: ReadContentFromZipFile* * @Description: Reading content of a ZIP file means that you list all entries* contained in the file without extracting them.* * * In the java.util.zip package, the ZipFile class can be used to* open and read a ZIP file like this:* * ZipFile zipFile = new ZipFile(zipFilePath); Enumeration<?* extends ZipEntry> entries = zipFile.entries();* * * Each entry is of type ZipEntry which provides the following* methods for reading information of an individual entry (to name* a few):* * getName(): returns the name of the entry in form of a relative* path* * getComment(): returns comment of the entry getCompressedSize():* returns the compressed size of the entry in bytes.* * getSize(): returns the normal size (uncompressed) of the entry* in bytes.* * isDirectory(): tells whether the entry is a directory or not.* * @author: Mr.Yang* * @date: 2017年9月7日 下午8:38:59*/ public class ReadContentFromZipFile {/*** * * @Title: readContentFromZipFile* * @Description: TODO* * @param zipFilePath* * @return: void*/public static void readContentFromZipFile(String zipFilePath) {try {ZipFile zipFile = new ZipFile(zipFilePath);Enumeration<? extends ZipEntry> entries = zipFile.entries();while (entries.hasMoreElements()) {ZipEntry entry = entries.nextElement();String name = entry.getName();long compressedSize = entry.getCompressedSize();long normalSize = entry.getSize();String type = entry.isDirectory() ? "DIR" : "FILE";System.out.println(name);System.out.format("\t %s - %d - %d\n", type, compressedSize, normalSize);}zipFile.close();} catch (IOException ex) {System.err.println(ex);}}public static void main(String[] args) {ReadContentFromZipFile.readContentFromZipFile("D:\\test.zip");} }總結
以上是生活随笔為你收集整理的Java-工具类之ZIP压缩解压的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java-Java I/O 字节流之Bu
- 下一篇: Spring-AOP @AspectJ进