首页 > Java开发 > java 压缩文件

java 压缩文件

/**
* 生成餐桌二维码
*
* @param filePath
* @return
*/
public static synchronized File encoderDeskTwoCode() {

// 压缩
try {
File inputDir = new File(imgPath);
FileOutputStream fos = new FileOutputStream(basePath + "/pics/"
+ resKey + ".zip");

// 过滤
ZipOutputStream zos = new ZipOutputStream(fos);

// 压缩
zip(inputDir.listFiles(), "", zos);

// 关闭
zos.close();

return new File(basePath + "/pics/" + resKey + ".zip");

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

return null;

}

 

public static void zip(File[] files, String baseFolder, ZipOutputStream zos)
throws Exception {

// 输入
FileInputStream fis = null;

// 条目
ZipEntry entry = null;

// 数目
int count = 0;
for (File file : files) {
if (file.isDirectory()) {

// 递归
zip(file.listFiles(), file.getName() + File.separator, zos);
continue;
}
entry = new ZipEntry(baseFolder + file.getName());

// 加入
zos.putNextEntry(entry);
fis = new FileInputStream(file);

// 读取
while ((count = fis.read(buffer, 0, buffer.length)) != -1)

// 写入
zos.write(buffer, 0, count);
}
}


本文固定链接: http://www.devba.com/index.php/archives/2737.html | 开发吧

报歉!评论已关闭.