【Java开源代码栏目提醒】:以下是网学会员为您推荐的Java开源代码-ZIPArchive.java,希望本篇文章对您学习有所帮助。
package mrgf;
import java.io.*;
import org.apache.tools.zip.*;
public class ZIPArchive {
public ZIPArchive() {
}
// 压缩文件
public void compress(String filePath, String outPath) {
// 创建输入流对象
InputStream in = null;
try {
in = new FileInputStream(filePath);
} catch (FileNotFoundException ex1) {
System.out.println("ex1,在创建输入流对象时抛出异常,内容如下:");
ex1.printStackTrace();
}
// 创建输出流对象
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream(outPath);
} catch (FileNotFoundException ex) {
System.out.println("ex,在创建输出流对象时抛出异常,内容如下:");
ex.printStackTrace();
}
// 创建ZIP压缩格式的输出流对象
ZipOutputStream zipOut = new ZipOutputStream(fileOut);
// 创建压缩文件进入点对象
ZipEntry zipEntry = new ZipEntry(new File(filePath).getName());
try {
zipOut.putNextEntry(zipEntry);
} catch (IOException ex2) {
System.out.println("ex2,在创建压缩文件进入点对象时抛出异常,内容如下:");
ex2.printStackTrace();
}
// 向压缩文件写入数据
byte b[] = new byte[512];
int len = 0;
try {
while ((len = in.read(b)) != -1) {
zipOut.write(b, 0, len);
}
} catch (IOException ex3) {
System.out.println("ex3,在生成
压缩文件时抛出异常,内容如下:");
ex3.printStackTrace();
}
// 关闭当前的压缩文件进入点对象
try {
zipOut.closeEntry();
} catch (IOException ex4) {
System.out.println("ex4,在关闭当前的压缩文件进入点对象时抛出异常,内容如下:");
ex4.printStackTrace();
}
// 关闭ZIP压缩格式的输出流对象
try {
zipOut.close();
} catch (IOException ex5) {
System.out.println("ex5,在关闭ZIP压缩格式的输出流对象时抛出异常,内容如下:");
ex5.printStackTrace();
}
// 关闭文件输入流
try {
in.close();
} catch (IOException ex6) {
System.out.println("ex6,在关闭文件输入流时抛出异常,内容如下:");
ex6.printStackTrace();
}
// 关闭文件输出流
try {
fileOut.close();
} catch (IOException ex7) {
System.out.println("ex6,在关闭文件输入流时抛出异常,内容如下:");
ex7.printStackTrace();
}
}
}