JAVA中ZIP压缩输入/输出流主要用到了java.util.zip包中的ZipOutputStream和ZipInputStream类。 如果要从ZIP压缩文件中读取某个文件,需要先找到对应该文件的目录进入点:
zin = new ZipInputStream(new FileInputStream("my.zip"));
ZipEntry entry = zin.getNextEntry();
同样如果要将文件压缩成ZIP格式,要创建对应该文件的目录进入点
ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(zipFileName))
zout.putNextEntry(new ZipEntry(path))
下面是一个压缩文件的例子:
package test2;
import java.io.*;
import java.util.zip.*;
public class MyZipTest { //创建类
public void zip(String zipFileName,File inputFile) throws Exception{
ZipOutputStream out = new ZipOutputStream(
new FileOutputStream(zipFileName)); //创建ZipOutputStream对象
System.out.println("压缩中···"); //打印
zip(out,inputFile,inputFile.getName());//调用方法
out.close(); //关闭输出流
}
public static String getFileNameNoEx(String filename) { //去掉扩展名,获取文件名
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot >-1) && (dot < (filename.length()))) {
return filename.substring(0, dot);
}
}
return filename;
}
private void zip(ZipOutputStream out, File f, String base)throws Exception{ //有参构造方法
// TODO Auto-generated method stub
if(f.isDirectory()) { //判断文件对象是否是路径
File[] fl = f.listFiles(); //创建路径下所有文件的File对象
for(int i=0;i
解压文件的例子:
import java.io.*;
import java.util.zip.*;
import java.util.Arrays;
public class Decompressing { // 创建文件
static String destinationPath = new String("C:"); //输入解压的目录
static String inputFilePath = new String("D:/hello.zip"); //输入源文件路径
static String myfname = (new File(inputFilePath)).getName();
static String myname = getFileNameNoEx(myfname);
public static String getFileNameNoEx(String filename) { //去掉扩展名,获取文件名
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot >-1) && (dot < (filename.length()))) {
return filename.substring(0, dot);
}
}
return filename;
}
public static void main(String[] temp) throws FileNotFoundException {
ZipInputStream zin = new ZipInputStream(new FileInputStream(inputFilePath));
//创建ZipInputStream对象
System.out.println("zip格式文件路径为:"+inputFilePath); //打印源文件路径
try { // try语句捕获可能发生的异常
zin = new ZipInputStream(new FileInputStream(inputFilePath));
// 实例化对象,指明要进行解压的文件
ZipEntry entry = zin.getNextEntry(); // 获取下一个ZipEntry
File outFile = null;
while (((entry = zin.getNextEntry()) != null)
&& !entry.isDirectory()) {
outFile = new File(destinationPath+"/"+myname ,entry.getName()); //获取文件目录
if(!outFile.exists()) {
File f = new File(outFile.getParent());
f.mkdirs(); //如果文件不存在则创建父类目录
System.out.println(f.getName());
}
FileOutputStream out = new FileOutputStream(outFile); //创建文件输出流
int b;
while((b=zin.read())!=-1) { //从输入流zin中读取数据
out.write(b); //写入文件
}
out.close(); //关闭输出流
zin.closeEntry(); // 关闭当前entry
System.out.println("已解压到路径: "
+destinationPath+"/"+myname+"/"+entry.getName());
}
zin.close(); // 关闭输入流
} catch (Exception e) {
e.printStackTrace();
}
}
}
作者小白,有不足之处还请评论指正