81,092
社区成员
发帖
与我相关
我的任务
分享
public static void zip() throws Exception{
FileInputStream file = new FileInputStream("D:\\EDC_FPT\\test.txt");
// 压缩文件 ,在这里调用压缩文件方法
// 定义压缩文件的名称
// 定义压缩输出流
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(new File("D:\\EDC_FPT\\test.zip")));
//实例化压缩输出流,并制定压缩文件的输出路径
zipOut.putNextEntry(new ZipEntry("D:\\EDC_FPT\\test.txt"));
int temp = 1;
while((temp = file.read()) != -1) {
zipOut.write(temp);
}
zipOut.close();
}
File file = null;
File parent = null;
ZipFile zipFile = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
zipFile = new ZipFile(fileName);
Enumeration<?> emu = zipFile.entries();
while (emu.hasMoreElements()) {
ZipEntry entry = (ZipEntry) emu.nextElement();
if (entry.isDirectory()) {
new File(targetPath + "/" + entry.getName()).mkdirs();
continue;
}
bis = new BufferedInputStream(zipFile.getInputStream(entry));
file = new File(targetPath + "/" + entry.getName());
parent = file.getParentFile();
if (parent != null && (!parent.exists()))
parent.mkdirs();
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, BUFFER);
int count;
byte data[] = new byte[BUFFER];
while ((count = bis.read(data, 0, BUFFER)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
}
new File(fileName).delete();
} catch (Exception e) {
logger.error("===method : unzip ERROR ===" + e.getMessage());
} finally {
file = null;
parent = null;
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
logger.error("===method : unzip BufferedOutputStream close ERROR ===" + e.getMessage());
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
logger.error("===method : unzip FileOutputStream close ERROR ===" + e.getMessage());
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
logger.error("===method : unzip BufferedInputStream close ERROR ===" + e.getMessage());
}
}
if (zipFile != null) {
try {
zipFile.close();
} catch (IOException e) {
logger.error("===method : unzip ZipFile close ERROR ===" + e.getMessage());
}
}
}