How to perform simple zip compression for a single file

Source: Internet
Author: User

Java has a zip package containing zipinputstream and zipoutputstream classes. We only need to read the file and then use zipoutputstream to output it. zipoutputstream is output in zipentry units, for Java's simple compression of a single file, see the following example:

Package COM. tjcyjd. commons; import Java. io. file; import Java. io. fileinputstream; import Java. io. fileoutputstream; import Java. io. inputstream; import java.util.zip. zipentry; import java.util.zip. zipoutputstream;/*** compress a single file * @ author YJD */public class filecompress {public static void zip (string inname, string outname) {file = new file (inname); int length = (INT) file. length (); byte [] B = new byte [length]; try {inputstream in = new fileinputstream (File); In. read (B); In. close ();} catch (exception e) {e. printstacktrace ();} Try {zipoutputstream Zout = new zipoutputstream (New fileoutputstream (new file (outname); Zout. setlevel (9); zipentry = new zipentry (file. getname (); Zout. putnextentry (zipentry); Zout. write (B); Zout. finish (); Zout. close ();} catch (exception e) {e. printstacktrace () ;}} public static void main (string [] ARGs) {string inname = "D:/yjd.txt"; string outname = "D:/yjd.zip "; filecompress.zip (inname, outname );}}

Zout. setlevel (9) is to set the compression level. The parameter 0-9 0 indicates no compression, and 9 indicates the compression is the most severe. If there is no need for efficiency, but the volume requirement is relatively high, it can be set to 9.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.