/***
* 压缩文件
* @param sourceFile 源文件
* @param zipFile 压缩后的文件
* @throws IOException
*/
public void createFileToZip(File sourceFile,File zipFile)throws IOException {
byte[] buf = new byte[1024];
//压缩文件名
File objFile = zipFile;
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFile));
ZipEntry ze = null;
//创建一个ZipEntry,并设置Name和其它的一些属性
ze = new ZipEntry(sourceFile.getName());
ze.setSize(sourceFile.length());
ze.setTime(sourceFile.lastModified());
//将ZipEntry加到zos中,再写入实际的文件内容
zos.putNextEntry(ze);
InputStream is = new BufferedInputStream(new FileInputStream(sourceFile));
int readLen = -1;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
zos.write(buf, 0, readLen);
}
is.close();
zos.close();
}
压缩文件代码
最新推荐文章于 2024-02-02 10:45:54 发布