废话不多说,直接上代码,如下是压缩核销方法
import org.springframework.stereotype.Service;
import javax.servlet.ServletException;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
压缩文件
*/
@Service
public class Compression {
//压缩文件
public void zipFile(List<File> files, ZipOutputStream outputStream) throws IOException, ServletException {
try {
int size = files.size();
// 压缩列表中的文件
for (int i = 0; i < size; i++) {
File file = (File) files.get(i);
zipFile(file, outputStream);
}
} catch (IOException e) {
throw e;
}
}
public void zipFile(File inputFile, ZipOutputStream outputstream) throws IOException, ServletException {
try {
if (inputFile.exists()) {
if (inputFile.isFile()) {
FileInputStream inStream = new FileInputStream(inputFile);
BufferedInputStream bInStream = new BufferedInputStream(inStream);
ZipEntry entry = new ZipEntry(inputFile.getName());
outputstream.putNextEntry(entry);
final int MAX_BYTE = 10 * 1024 * 1024; // 最大的流为10M
long streamTotal = 0; // 接受流的容量
int streamNum = 0; // 流需要分开的数量
int leaveByte = 0; // 文件剩下的字符数
byte[] inOutbyte; // byte数组接受文件的数据
streamTotal = bInStream.available(); // 通过available方法取得流的最大字符数
streamNum = (int) Math.floor(streamTotal / MAX_BYTE); // 取得流文件需要分开的数量
leaveByte = (int) streamTotal % MAX_BYTE; // 分开文件之后,剩余的数量
if (streamNum > 0) {
for (int j = 0; j < streamNum; ++j) {
inOutbyte = new byte[MAX_BYTE];
// 读入流,保存在byte数组
bInStream.read(inOutbyte, 0, MAX_BYTE);
outputstream.write(inOutbyte, 0, MAX_BYTE); // 写出流
}
}
// 写出剩下的流数据
inOutbyte = new byte[leaveByte];
bInStream.read(inOutbyte, 0, leaveByte);
outputstream.write(inOutbyte);
outputstream.closeEntry(); // Closes the current ZIP entry
// and positions the stream for
// writing the next entry
bInStream.close(); // 关闭
inStream.close();
}
} else {
throw new ServletException("文件不存在!");
}
} catch (IOException e) {
throw e;
}
}
}
调用方法可以自己实现,如我是压缩某个文件夹下所有文件可以这样实现
/**
* 下载的路径path
* 压缩文件路径及名称 downFileName 如d://abc.zip
* */
public String compressionFiles(String path, String downFileName)
throws ServletException, IOException {
List<File> files = new ArrayList<File>();
File Allfile = new File(path);
if (Allfile.exists()) {
File[] fileArr = Allfile.listFiles();
for (File file : fileArr) {
files.add(file);
}
}else{
return null;
}
File fileZip = new File(downFileName );
// 文件输出流
FileOutputStream outStream = new FileOutputStream(fileZip);
// 压缩流
ZipOutputStream toClient = new ZipOutputStream(outStream);
// toClient.setEncoding("gbk");
zipFile.zipFile(files, toClient);
toClient.close();
outStream.close();
return downFileName;
}
这里返回了压缩文件所在路径,可以调用下载方法下载即可。