Comprimere files in formato ZIP con Java

This page was exported from - JPinup
Export date: Thu Jun 1 11:56:14 2017 / +0000 GMT
Comprimere files in formato ZIP con Java
La soluzione più semplice per gestire file ZIP tramite Java è basata sulla libreria java.util.zip, ottima per comprimere i nostri file.
Di seguito un semplice esempio.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipClass {
// lista entry è la lista di tutti i path dei file che lo zip deve contenere
public void creaZip(String fileZip, final ArrayList<String> listaEntry)
throws Exception {
final File f = new File(fileZip);
FileOutputStream fileOutputStream = new FileOutputStream(f);
final ZipOutputStream out = new ZipOutputStream(fileOutputStream);
for (String zipEntry : listaEntry) {
addToZipFile(zipEntry, out);
}
out.close();
fileOutputStream.close();
}
public static void addToZipFile(String fileName, ZipOutputStream zos)
throws FileNotFoundException, IOException {
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
public static void main(String[] args) throws Exception {
ZipClass zipClass = new ZipClass();
ArrayList<String> listaEntry = new ArrayList<>();
listaEntry.add("C:\tmp\test.docx");
listaEntry.add("C:\tmp\prova.bmp");
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com
| Page 1/2 |
This page was exported from - JPinup
Export date: Thu Jun 1 11:56:14 2017 / +0000 GMT
zipClass.creaZip("c:\tmp\zippojpinup.zip", listaEntry);
}
}
Scarica progetto
Output as PDF file has been powered by [ Universal Post Manager ] plugin from www.ProfProjects.com
| Page 2/2 |