直接上代码
写:
public class Test {
public static void main(String[] args) throws IOException {
//压缩两个文件到一个压缩包中
//目标压缩文件输出流,文件一开始并不存在
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("C:\\Users\\86150\\Desktop\\test.zip")));
//每写入一个文件前,必须调用该函数,参数是在压缩文件中的相对路径
out.putNextEntry(new ZipEntry( "level1\\test.txt"));
//打开要压缩的第一个文件的输入流
InputStream in = new BufferedInputStream(new FileInputStream("C:\\Users\\86150\\Desktop\\test.txt"));
//把输入流写到输出流
in.transferTo(out);
//关闭输入流
in.close();
//同上
out.putNextEntry(new ZipEntry( "level1\\test1.txt"));
InputStream in1 = new BufferedInputStream(new FileInputStream("C:\\Users\\86150\\Desktop\\test1.txt"));
in1.transferTo(out);
in1.close();
//关闭目标压缩文件输出流
out.close();
}
}
读:
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Test1 {
public static void main(String[] args) {
{
ZipInputStream in;
try {
//给压缩文件输入流加上Zip包装流
in = new ZipInputStream(new BufferedInputStream(new FileInputStream("C:\\Users\\86150\\Desktop\\test.zip")));
//下一个压缩文件条目,没有返回null
ZipEntry zipEntry = in.getNextEntry();
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
in.transferTo(out);
System.out.println(out.toString());
//重置字节数组输入流
out.reset();
ZipEntry zipEntry1 = in.getNextEntry();
in.transferTo(out);
System.out.println(out.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}