Wednesday 25 July 2018

Creating Zip File of Multiple Text File

This class will help you to create Zip File of List of Files.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class DemoZip {

private ZipOutputStream zos;
public static void main(String[] args) throws IOException {
File file1 = new File("/home/pojke/ZipFile/a.txt");
File file2 = new File("/home/pojke/ZipFile/b.txt");
File file3 = new File("/home/pojke/ZipFile/c.txt");
ArrayList<File> files = new ArrayList<>();
files.add(file1);
files.add(file2);
files.add(file3);
DemoZip zip = new DemoZip();
zip.zipFile("/home/pojke/ZipFile/zipFile.zip", files);
}
private void zipFile(String outputZipFileName, ArrayList<File> files) throws IOException, IOException {
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(outputZipFileName);
zos = new ZipOutputStream(fos);
files.stream().forEach(file ->{
try(
FileInputStream fis = new FileInputStream(file)) {
zos.putNextEntry(new ZipEntry(file.getName()));

int len;
while((len=fis.read(buffer))>0) {
zos.write(buffer,0,len);
}
zos.closeEntry();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
});
zos.close();
fos.close();

System.out.println("Zip File Created Successfully");
}

}

1 comment: