📄 压缩类的例子.java
字号:
import java.io.*;
import java.util.*;
import java.util.zip.*;
public class zip2
{
void zip(String[] filename) throws IOException
{
FileOutputStream f = new FileOutputStream("zip_test.zip ");//产生流
ZipOutputStream zop = new ZipOutputStream(f);
zop.setMethod(ZipOutputStream.DEFLATED);//设置压缩级别
for (int i = 0; i < filename.length; i++)//for语句作用是判断传入有几个文件
{
FileInputStream fs = new FileInputStream(filename[i]);
ZipEntry ze = new ZipEntry(filename[i]);
System.out.println(fs.available());
ze.setSize((long)fs.available());//(long)是强行转换类型
zop.putNextEntry(ze);
byte[] filebyte = new byte[fs.available()];//读取文件的大小fs.available()
fs.read(filebyte);
fs.close();
zop.write(filebyte);
}
zop.close();
}
//unzip
void unzip(String zipfilename) throws IOException//因为这里所解压的是一个包所以不须要string[]
{
System.out.println(zipfilename);
FileInputStream fis= new FileInputStream(zipfilename);
ZipInputStream zis = new ZipInputStream(fis);
ZipEntry ze = zis.getNextEntry();
while (ze != null)
{
System.out.println(ze);
FileOutputStream fw = new FileOutputStream( ze.getName());//如果你要加路径你就可以这样写
DataInputStream ds = new DataInputStream(zis); //FileOutputStream fw = new FileOutputStream( "D:\\backup\\www\\zip\\"+ze.getName());
int rdlen;
int filelen = 16298;//这里的16298是所要解压文件的大小比如test.jpg的大小为16298kb这里就写入这个数
byte[] temp = new byte[filelen] ;
int i=0;
for(i=0;i< filelen ;i++)
{
rdlen = zis.read(temp,i,1);//这里zis.read(temp,i,1)中的数字1代表每次读取一个字节i代表temp[]的第几位
//要注意的是.read这个参数能直接的起到赋值作用:把i中的值赋给temp
}
fw.write(temp);
fw.close();
ze = zis.getNextEntry();
}
zis.close();
}
//接口的调用是,当压缩时注释掉zzip.unzip(args[0]);测试java zip2 args[0] args[2].....这里的args指代的是你所要压缩的几个文件
//zip函数中的for语句做用就是查看你有几个文件要压缩比如:所要压缩的文件是test.jpg,那么就测java zip2 test.jpg
//当解压时注释掉zzip.zip(args);测试java zip2 args这里的args指的是zip_test.zip这个压缩包,测java zip2 zip_test.jpg
public static void main(String[] args) throws IOException
{
zip2 zzip = new zip2();
//zzip.zip(args);
zzip.unzip(args[0]);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -