压缩流:
首先肯定是要读一个文件,然后给它压缩,程序步骤要清楚,
/**
*
*
- 这里做的是压缩的单个文件
- @author dch
*/
//压缩文件
public class TestZip {
/* 压缩文件
* 将一个或者多个文件通过,放入到另一个XXX.zip的文件中(复制)
* 过程: 先指定文件,获取一个输入流,在写到zip (ZipOutputStream)
* 对于zip中每个文件,对应的一个文件实体ZipEntry
*
* 步骤:
*
* 输入流--放入zipEntry--再写出到zip文件夹中
*
*/
public static void main(String[] args) throws IOException {
//获取文件的输入流
File file = new File("d://aa.txt");
InputStream is = new FileInputStream(file);
//创建一个文件的输出的压缩流 ZipOutputStream
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("d://压缩测试文件夹//我的压缩文件.zip"));
//将需要压缩的文件,先转成一个ZipEntry才可以压缩
zos.putNextEntry(new ZipEntry(file.getName()));
//这个file.getname是得到aa.txt的名字
//从而保证文件名的一致
//复制
byte [] b = new byte[100];
int len = 0;
while((len=is.read(b))!=-1){
zos.write(b, 0, len);
}
System.out.println("压缩成功");
zos.close();
is.close();
}
}
这里是要压缩的是文件夹里面的所有文件,
不仅仅是压缩单个文件夹
/**
*
- 这里是要压缩的是文件夹里面的所有文件,
- 不仅仅是压缩单个文件夹
- @author dch
*/
//压缩文件
public class TestZip2 {
public static void main(String[] args) throws Exception {
File file = new File("d://测试文件夹/a");
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("d://压缩测试文件夹/a.zip"));
getCount(file, zos);
zos.close();
}
//这里的方法是得到我们要是压缩的文件,判别是文件夹还是文件
public static void getCount(File file,ZipOutputStream zos) throws Exception{
//判断是不是文件,如果是文件就压缩
if(file.isFile()){
getZip(file,zos);
}else{
//如果是目录的话,就继续找
File[] files = file.listFiles();//这里是抽象路径数组
for (File f : files) {
//递归调用
getCount(f, zos);
}
}
}
//这里是将文件进行压缩
public static void getZip(File file,ZipOutputStream zos) throws Exception{
//要压缩的文件路径 file
//同样是文件的输入流也就是 inputstream
InputStream is = new FileInputStream(file);
//创建一个文件输出的压缩流 ZipOutputStream
//这里实现的是将我要压缩的文件夹里面的所有文件压缩的了我的目标地址,
//但是这里却没有分层级,接下来就是要解决将文件压缩到对应的文件夹中,
//从而使和要压缩的文件夹的分层达到一致.
zos.putNextEntry(new ZipEntry(file.getName()));
//复制
byte [] b = new byte[100];
int len = 0;
while((len=is.read(b))!=-1){
zos.write(b, 0, len);
}
System.out.println("压缩成功");
is.close();
}
}
解压缩文件
/**
*
- @author dch
*/
//解压缩文件
public class TestZipInputStream {
public static void main(String[] args) throws IOException {
//先获取到zip的文件
ZipFile zf = new ZipFile("d://压缩测试文件夹/a.zip");
File outfile=new File("d://测试文件夹/bb");
if(!outfile.exists()){
outfile.mkdirs();
}
//还是要先从文件里面读所以是inputstream
InputStream is = new FileInputStream("d://压缩测试文件夹/a.zip");
ZipInputStream zis = new ZipInputStream(is);
ZipEntry entry = zis.getNextEntry();
if(!entry.isDirectory()){
//这里判断是不是文件
//获取到文件目录的输入流
InputStream entryis = zf.getInputStream(entry);
//自定义输出流
OutputStream ops = new FileOutputStream(outfile.getPath()+File.separator+entry.getName());
//文件复制
int len=0;
while((len=entryis.read())!=-1){
ops.write(len);
}
//关闭流
ops.close();
entryis.close();
}
}
}