依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
工具类:
FileZipUtil {
(ZipOutputStream zipFile fileString dir) Exception {
(file.isDirectory()) {
File[] fileArray = file.listFiles()(fileArray == ) {
}
zip.putNextEntry(ZipEntry(dir + ))dir = dir.length() == ? : dir + (File f : fileArray) {
(zipfdir + f.getName())}
} {
BufferedInputStream bis = BufferedInputStream(FileInputStream(file))String pngName = file.getName()ZipEntry entry = ZipEntry(pngName)zip.putNextEntry(entry)zip.write(FileUtils.(file))IOUtils.(bis)zip.flush()zip.closeEntry()}
}
[] (String sourceFilePath) Exception{
ByteArrayOutputStream outputStream = ByteArrayOutputStream()ZipOutputStream zip = ZipOutputStream(outputStream)File file = File(sourceFilePath)(zipfile)IOUtils.(zip)outputStream.toByteArray()}
(HttpServletResponse responseString sourceFilePath) {
SimpleDateFormat sdf = SimpleDateFormat()String filePrefix = sdf.format(Date())String downloadName = filePrefix + {
OutputStream out = response.getOutputStream()[] data = (sourceFilePath)response.reset()response.addHeader()response.setHeader()response.setHeader(+ downloadName)response.addHeader(+ data.)response.setContentType()IOUtils.(dataout)out.flush()out.close()} (Exception e) {
e.printStackTrace()}
}
}
使用:
String path = System.getProperty("user.dir");
String filePath = path+"/file";
String pngPath = filePath+"/png";
FileZipUtil.exportZip(response, pngPath);