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.