JAVA(二)将文件转换成ZIP文件

一.执行的主函数

  • 读取文件的流
public void zip() throws Exception {
    //文件输出流
    FileOutputStream fos = new     FileOutputStream("d:/arch/xxx.xar");
    //压缩流
    ZipOutputStream zos = new ZipOutputStream(fos);
}
  • 定义字符串,读取文件夹中的文件列表
String[] arr = {
            "d:/arch/1.jpg",
            "d:/arch/2.txt",
            "d:/arch/3.xml"
    };
  • 读取文件文件名,调用功能函数。
for(String s : arr){
        addFile(zos , s);
    }
    zos.close();
    fos.close();
    System.out.println("over");
  • 循环向zos中添加条目
public static void addFile(ZipOutputStream zos , String path) throws Exception{
    File f = new File(path);
    zos.putNextEntry(new ZipEntry(f.getName()));
    FileInputStream fis = new FileInputStream(f);
    byte[] bytes = new byte[fis.available()];
    fis.read(bytes);
    fis.close();
    
    zos.write(bytes);
    zos.closeEntry();
}

四.解压方法

public void unzip() throws Exception{
    //
    FileInputStream fis = new FileInputStream("d:/arch/xxx.zip");
    //
    ZipInputStream zis = new ZipInputStream(fis);
    //
    ZipEntry entry = null ;
    byte[] buf = new byte[1024];
    int len = 0 ;


while((entry = zis.getNextEntry()) != null){
        String name = entry.getName();
                读取文件名,然后执行戒指解压方法
        FileOutputStream fos = new FileOutputStream("d:/arch/unzip/" + name);
        while((len = zis.read(buf)) != -1){
                        解压用write
            fos.write(buf, 0, len);
        }
        fos.close();
    }
    zis.close();
    fis.close();
}

你可能感兴趣的:(JAVA(二)将文件转换成ZIP文件)