最近碰到了关于Java实现文件压缩的问题,在这里记录下代码:
public File fileCompress(File file){
File zipfile = new File(FilenameUtils.getFullPath(file.getAbsolutePath())
.concat(FilenameUtils.getBaseName(file.getAbsolutePath()))
.concat(".zip"));
BufferedInputStream br = null;
ZipOutputStream zos = null;
try{
zos = new ZipOutputStream(new FileOutputStream(zipfile));
zos.putNextEntry(new ZipEntry(file.getName()));
br = new BufferedInputStream(new FileInputStream(file));
byte[] by = new byte[2 * 1024 * 1024];
int c = 0;
while((c = br.read(by)) != -1) {
zos.write(by,0,c);
}
zos.flush();
} catch(Exception e){
} finally {
if(br != null) {
try{
br.close();
} catch (IOException e) {
}
}
if(zos != null) {
try{
zos.close();
} catch (IOException e) {
}
}
}
return zipfile;
}