RAR

需要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();

}

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容