Java generates compressed files

Source: Internet
Author: User

In the course of work, you need to generate a compressed file for a folder, and then provide it to the user for download. Therefore, I wrote a tool class for compressing files. This tool class supports compression of a single file and folder. Put the Code:

CompressedFile (String resourcesPath, String targetPath) File resourcesFile = File (resourcesPath); File targetFile = File (targetPath );(! String targetName = resourcesFile. getName () + ". zip "; FileOutputStream outputStream = FileOutputStream (targetPath +" \ "+ ZipOutputStream out = ZipOutputStream (createCompressedFile (out, resourcesFile," "createCompressedFile (ZipOutputStream out, File file, String dir) file [] files = out. putNextEntry (ZipEntry (dir + "/" dir = dir. length () = 0? "": Dir + "/" (I = 0; I <files. length; I ++ createCompressedFile (out, files [I], dir + files [I]. getName (); {FileInputStream FCM = out. putNextEntry (j = 0 [] buffer = [1024 (j = FCM. read (buffer)> 0 out. write (buffer, 0 CompressedFileUtil compressedFileUtil = compressedFileUtil. compressedFile ("G: \ zip", "F: \ zip" System. out. println ("the compressed file has been generated... "} System. out. println ("failed to generate the compressed file... "}

The running result is as follows:

File directory structure before compression:

 If java.util.zip under java.utilis used for packaging, Chinese garbled characters may occur because the java zip method does not support encoding format changes. We can use the zip tool class under ant. java for packaging. So you need to import ant. jar to the lib directory of the project.

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.