java压缩文件或文件夹

/**
* @param inputFilePath
*            压缩 文件或文件夹的绝对路径
* @param outFilePath
*            压缩文件的输出路径
* */
public void zip(String inputFilePath, String outFilePath) throws Exception {
FileOutputStream output = null;
ZipOutputStream zipout = null;
try {
output = new FileOutputStream(outFilePath);
File inputFile = new File(inputFilePath);
if (!inputFile.exists()) {
_log.error(inputFilePath + " not found");
throw new FileNotFoundException(inputFilePath);
}
zipout = new ZipOutputStream(output);
executeZip(zipout, inputFile, "");
} catch (FileNotFoundException ex) {
_log.error(outFilePath + " not found |", ex);
throw new FileNotFoundException(outFilePath);
} finally {
closeStream(output, zipout);
}

}

/** 压缩 文件夹 */
private void executeZip(ZipOutputStream out, File file, String base)
throws Exception {
if (file.isDirectory()) {
File[] array = file.listFiles();
out.putNextEntry(new ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < array.length; i++) {
executeZip(out, array[i], base + array[i].getName());
}
} else {
zipFile(out, file, base);
}
}



/** 压缩 文件 */
private void zipFile(ZipOutputStream outStream, File file, String base)
throws IOException {
putEntry(outStream, file, base);

FileInputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
int c = 0;
byte[] bt = new byte[SIZE];
while ((c = inputStream.read(bt)) != -1) {
outStream.write(bt, 0, c);
}
} catch (FileNotFoundException ex) {
_log.error(file.getPath() + " not found |", ex);
throw ex;
} catch (IOException e) {
_log.error("IOException in zipFile |", e);
throw e;
} finally {
if (null != inputStream) {
inputStream.close();
}
}
}

private void putEntry(ZipOutputStream outStream, File file, String base)
throws IOException {
if (base.length() > 0) {
outStream.putNextEntry(new ZipEntry(base));
} else {
outStream.putNextEntry(new ZipEntry(file.getName()));
}
}

你可能感兴趣的:(java,zip)