There is a bit more problem with the code for a zip compressed file on the Web. Now refactor. The main changes are as follows: Add private constructor System.out.println output log to Logger.info output remove Run-time exception more than 3 If/for/while code control is used in 3 and within JDK7 Try-with-resources, eliminating the need to manually shut down resources and streamline code line comments with//, instead of/*/using JDK7 diamond syntax, and code list filelist = new ArrayList (); change to list filelist = new Arraylist<> ();
Before refactoring:
Package com.ylchou.utlis;
Import java.io.*;
Import java.util.ArrayList;
Import java.util.List;
Import Java.util.zip.ZipEntry;
Import Java.util.zip.ZipOutputStream;
/** * Created by Ylchou on 18/3/19.
* * Public class Ziputils {private static final int buffer_size = 2 * 1024; /** * Compressed into Zip Method 1 * @param srcdir Compressed Folder path * @param out compressed file output stream * @param keepdirstructure whether to keep the original directory knot
Construct, true: Preserve directory structure;
* False: All files run to compressed package root directory (note: The directory structure may have a file with the same name, compression failure) * @throws RuntimeException compression failure throws a Run-time exception */public static void Tozip (String srcdir, OutputStream out, Boolean keepdirstructure) throws Runtimeexc
eption{Long start = System.currenttimemillis ();
Zipoutputstream Zos = null;
try {zos = new Zipoutputstream (out);
File SourceFile = new file (Srcdir);
Compress (Sourcefile,zos,sourcefile.getname (), keepdirstructure); Long end = System.currenttimemillis();
SYSTEM.OUT.PRINTLN ("Compression complete, time consuming:" + (End-start) + "MS");
catch (Exception e) {throw new RuntimeException ("Zip error from ziputils", e);
}finally{if (Zos!= null) {try {zos.close ();
catch (IOException e) {e.printstacktrace (); /** * Compressed into Zip Method 2 * @param srcfiles List of files to compress @param out compression File output stream * @throws RuntimeException compression failure throws runtime exception/public static void Tozip (list<file> srcfiles, output
Stream out) throws RuntimeException {Long start = System.currenttimemillis ();
Zipoutputstream Zos = null;
try {zos = new Zipoutputstream (out);
for (File srcfile:srcfiles) {byte[] buf = new Byte[buffer_size];
Zos.putnextentry (New ZipEntry (Srcfile.getname ()));
int Len; FileInputStream in = new FileInputStream (srcfile);
while (len = In.read (buf))!=-1) {zos.write (buf, 0, Len);
} zos.closeentry ();
In.close ();
Long end = System.currenttimemillis ();
SYSTEM.OUT.PRINTLN ("Compression complete, time consuming:" + (End-start) + "MS");
catch (Exception e) {throw new RuntimeException ("Zip error from ziputils", e);
}finally{if (Zos!= null) {try {zos.close ();
catch (IOException e) {e.printstacktrace ();
/** * Recursive compression method * @param sourcefile source file * @param zos Zip output stream
* @param name Compressed @param keepdirstructure whether the original directory structure is preserved, true: preserve the directory structure; * False: All files run to the compressed package root directory (note: The directory structure may have a file with the same name, compression failed) * @throws Exception * * Private STA Ticvoid Compress (File sourcefile, Zipoutputstream Zos, String name, Boolean keepdirstructure
) throws exception{byte[] buf = new Byte[buffer_size]; if (Sourcefile.isfile ()) {//Add a zip entity to the zip output stream, the name of the file named Zip entity in the constructor Zos.putnextentry (new ZipEntry (n
AME));
Copy file to the zip output stream int len;
FileInputStream in = new FileInputStream (sourcefile);
while (len = In.read (buf))!=-1) {zos.write (buf, 0, Len);
}//Complete the entry zos.closeentry ();
In.close ();
else {file[] listfiles = Sourcefile.listfiles (); if (Listfiles = = NULL | | listfiles.length = 0) {//when the original file structure needs to be preserved, an empty folder needs to be processed if (Keepdirstru
Cture) {//Empty folder processing Zos.putnextentry (new ZipEntry (name + "/")); No files, no copy zo for filesS.closeentry ();
}}else {for (file file:listfiles) {//Determine if the original file structure needs to be preserved if (keepdirstructure) {//Note: File.getname () must precede with the name of the parent folder plus a slash,/ In the end, the original file structure cannot be kept in the compressed package, that is, all files are run to the compressed package root directory compress (file, Zos, name + "/" + File.getname (), keepdirstruct
URE);
else {compress (file, Zos, File.getname (), keepdirstructure);
"}}}} public static void Main (string[] args) throws Exception {
/** Test Compression Method 1/FileOutputStream fos1 = new FileOutputStream (New File ("/users/ylchou/downloads/mytest02.zip");
Ziputils.tozip ("/users/ylchou/downloads/mail_test", fos1,true);
/** Test Compression Method 2 */list<file> filelist = new arraylist<file> (); Filelist.add (New File ("/users/ylchou/downloads/mail_test/Aaaa.txt "));
Filelist.add (New File ("/users/ylchou/downloads/mail_test/jdk7u80.txt"));
FileOutputStream Fos2 = new FileOutputStream (New File ("/users/ylchou/downloads/mytest03.zip"));
Ziputils.tozip (filelist, Fos2); }
}
After refactoring:
Package com.ylchou.utlis;
Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import java.io.*;
Import java.util.ArrayList;
Import java.util.List;
Import Java.util.zip.ZipEntry;
Import Java.util.zip.ZipOutputStream;
/** * Compression Tool class * Created by Ylchou on 18/3/19.
* * Public class Ziputils {private static final Logger Logger = Loggerfactory.getlogger (Ziputils.class);
private static final int buffer_size = 2 * 1024; Private Ziputils () {}/** * compressed into Zip Method 1 * @param srcdir Compressed Folder path * @param out compressed file output stream * @par
Am Keepdirstructure preserve the original directory structure, true: preserve the directory structure; * False: All files run to compressed package root directory (note: The directory structure may have a file with the same name, compression fails)/public static void Tozip (String srcd
IR, OutputStream out, Boolean keepdirstructure) {Long start = System.currenttimemillis ();
Try (zipoutputstream Zos = new Zipoutputstream (out)) {file SourceFile = new File (srcdir); Compress (Sourcefile,zos,sourcefile.getName (), keepdirstructure);
Long end = System.currenttimemillis ();
Logger.info ("Compression complete, time consuming:" + (End-start) + "MS");
catch (Exception e) {logger.info ("Zip error from ziputils", e); /** * Compressed into Zip Method 2 * @param srcfiles List of files to be compressed * @param out compressed file output stream/public
static void Tozip (List<file> srcfiles, outputstream out) {Long start = System.currenttimemillis (); Try (zipoutputstream Zos = new Zipoutputstream (out);)
{for (File srcfile:srcfiles) {byte[] buf = new Byte[buffer_size];
Zos.putnextentry (New ZipEntry (Srcfile.getname ()));
int Len;
FileInputStream in = new FileInputStream (srcfile);
while (len = In.read (buf))!=-1) {zos.write (buf, 0, Len);
} zos.closeentry ();
In.close (); Long end =System.currenttimemillis ();
Logger.info ("Compression complete, time consuming:" + (End-start) + "MS");
catch (Exception e) {logger.info ("Zip error from ziputils", e); /** * Recursive compression method * @param sourcefile source file * @param zos Zip output stream * @param name compressed
Name * @param keepdirstructure whether the original directory structure is preserved, true: preserve the directory structure; * False: All files run to the compressed package root directory (note: The directory structure may have a file with the same name, compression failed) * @throws Exception * * Private STA tic void Compress (File sourcefile, Zipoutputstream Zos, String name, Boolean Keepdirstruc
ture) throws exception{if (Sourcefile.isfile ()) {//file byte[] buf = new Byte[buffer_size];
Adds a zip entity to the zip output stream, with the name Zos.putnextentry (new ZipEntry (name)) of the file named the zip entity in the constructor;
Copy file to the zip output stream int len;
FileInputStream in = new FileInputStream (sourcefile);
while (len = In.read (buf))!=-1) { Zos.write (buf, 0, Len);
}//Complete the entry zos.closeentry ();
In.close ();
Return
}//directory file[] listfiles = Sourcefile.listfiles (); if (listfiles = null | | listfiles.length = = 0) {//empty directory///need to keep the original file structure, the empty folder needs to be processed if (keepdirstructu
RE) {//Empty folder processing Zos.putnextentry (new ZipEntry (name + "/"));
No files, no copy zos.closeentry (); }}else {//non-empty directory for (file file:listfiles) {//Determine whether the original file structure needs to be retained if (k Eepdirstructure) {//Note: File.getname () preceded by the name of the parent folder with a slash,//or the last compressed package can not retain the original file structure,
That is: All files are run to the compressed package root directory under the Compress (file, Zos, name + "/" + File.getname (), keepdirstructure);
else {compress (file, Zos, File.getname (), keepdirstructure);
} }} public static void Main (string[] args) throws Exception {//Test compression Method 1 Fileout
Putstream fos1 = new FileOutputStream (New File ("/users/ylchou/downloads/mytest02.zip"));
Ziputils.tozip ("/users/ylchou/downloads/mail_test", fos1,true);
Test compression Method 2 list<file> filelist = new arraylist<> ();
Filelist.add (New File ("/users/ylchou/downloads/mail_test/aaaa.txt"));
Filelist.add (New File ("/users/ylchou/downloads/mail_test/jdk7u80.txt"));
FileOutputStream Fos2 = new FileOutputStream (New File ("/users/ylchou/downloads/mytest03.zip"));
Ziputils.tozip (filelist, Fos2); }
}
Pom File:
<?xml version= "1.0" encoding= "UTF-8"?> <project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "HTT" P://www.w3.org/2001/xmlschema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0 Http://maven.apach E.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupid>com.ylchou</grou pid> <artifactId>private-tools</artifactId> <version>1.0</version> <dependencie s> <dependency> <groupId>com.alibaba</groupId> <artifactid>fast json</artifactid> <version>1.2.6</version> </dependency> <dependenc Y> <groupId>org.apache.httpcomponents</groupId> <artifactid>httpclient</ar
tifactid> <version>4.5.2</version> </dependency> <dependency> <groupid>org.Apache.httpcomponents</groupid> <artifactId>httpmime</artifactId> <version>
;4.5.2</version> </dependency> <!--log start--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <vers ion>${slf4j.version}</version> </dependency> <dependency> <groupId> Org.apache.logging.log4j</groupid> <artifactId>log4j-core</artifactId> <versi on>${log4j2.version}</version> </dependency> <dependency> <groupId> Org.apache.logging.log4j</groupid> <artifactId>log4j-api</artifactId> <versio n>${log4j2.version}</version> </dependency> <dependency> <groupid>o rg.apache.logging.log4j≪/groupid> <artifactId>log4j-slf4j-impl</artifactId> <version>${log4j2.vers ion}</version> </dependency> <dependency> <groupid>org.apache.logging .log4j</groupid> <artifactId>log4j-web</artifactId> <version>${log4j2.vers
Ion}</version> </dependency> <!--adapter log4j--> <dependency>
<groupId>org.slf4j</groupId> <artifactId>log4j-over-slf4j</artifactId>
<version>1.7.12</version> </dependency> <!--adapter Commons-logging--> <dependency> <groupId>org.slf4j</groupId> <artifactid>jcl-over-slf4j</a
Rtifactid> <version>1.7.12</version> </dependency> <!--log end--> </dependencies&Gt <properties> <log4j2.version>2.4.1</log4j2.version> <slf4j.version>1.7.12</slf4 J.version> </properties> </project>
The results are as follows: