需要ant.jar包
链接: https://pan.baidu.com/s/1uLQdjit3gjgBpWaVRRXNoA 提取码: ydn7
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipFile;
public class Main {
public static void main(String[] args)throws IOException {
System.out.println("Hello World!");
File one =new File("//home//weikun//文档//1996.tar.gz");
Date now=new Date();
SimpleDateFormat time=new SimpleDateFormat("YYY-MM-DD");
System.out.println(time.format(now));
File two=new File(time.format(now)+".rar");
FileOutputStream fos=new FileOutputStream(two);
CheckedOutputStream cos=new CheckedOutputStream(fos,new CRC32());
ZipOutputStream zos=new ZipOutputStream(cos);
zos.setEncoding("GBK");
ZipFile(zos,one);
zos.close();
cos.close();
fos.close();
System.out.println("压缩完成");
System.out.println(two.getAbsolutePath());
}
public static void ZipFile(ZipOutputStream zos,File file)throws IOException {
if(file.isDirectory()){
//压缩文件的目录结构
zos.putNextEntry(new ZipEntry(file.getPath().substring(file.getPath().indexOf(file.getName()))+File.separator));
for (File f:file.listFiles()){
ZipFile(zos,f);
}
}
//打印输出正在压缩的文件
System.out.println("正在压缩文件:"+file.getName());
//创建压缩文件
zos.putNextEntry(new ZipEntry(file.getPath().substring(file.getPath().indexOf(file.getName()))));
//用字节方式读取源文件
InputStream is =new FileInputStream(file.getPath());
//创建一个缓存区
BufferedInputStream bis =new BufferedInputStream(is);
//字节数组,每次读取1024个字节
byte [] b =new byte[1024];
//循环读取,边读边写
while(bis.read(b)!=-1)
{
zos.write(b);//写入压缩文件
}
//关闭流
bis.close();
is.close();
}
}