Java做成Zip文件,Java实现压缩文件

时间:2022-11-26 11:52:30
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;



String outputpath[] = new String[2];
outputpath[0] = "C:/ziptest/1.csv";
outputpath[1] = "C:/ziptest/2.csv";

String outputfile[] = new String[]{
        "zipfile_1.csv",
        "zipfile_2.csv"};

String zipfile = "C:/tmpDownLoadFile.zip";

FileInputStream inputFile = null;

ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipfile));
ZipEntry zipEntry = null;

byte[] buf = new byte[2048];
int len = 0;

for (int i = 0; i < outputpath.length; i++) {
    inputFile = new FileInputStream(outputpath[i]);
    zipEntry = new ZipEntry(outputfile[i]);
    zipOutputStream.putNextEntry(zipEntry);
    
    len = 0;
    while ((len = inputFile.read(buf)) != -1) {
        zipOutputStream.write(buf, 0, len);
    }
    inputFile.close();
    
    zipOutputStream.closeEntry();
}
zipOutputStream.close();