sábado, 18 de outubro de 2008

Compactar e descompactar

Classe utilitária para compactar e descompactar arquivos zip apartir de um stream de dados



/**
* Compact and Unpack Zip files
*
* @author Clayton.Passos
*
*/
public class Zip implements ICompactOperation {
private static final int BUFFER_SIZE = 1024;

/**
* Compacta os arquivos da lista armazenando-os no output
*
* @param fileLst
* List
* @param dataOut
*
* @param pathComplete
* Se for verdadeiro guardará todo o caminho até o arquivo

* Se for falso armazenará apenas o arquivo, sem o caminho
* @throws IOException
*/
public static void compact(List fileLst, DataOutputStream dataOut,
boolean pathComplete) throws IOException {
ZipOutputStream out = new ZipOutputStream(dataOut);
out.setLevel(9);

// Create a buffer for reading the files
byte[] BUFFER = new byte[BUFFER_SIZE];

// Compress the files
FileInputStream in;
File file;
for (int i = 0; i < fileLst.size(); i++) {
file = (File) fileLst.get(i);
in = new FileInputStream(file);

// Add ZIP entry to output stream.
ZipEntry entry;
if (pathComplete) { // Complete path in zip file
entry = new ZipEntry(file.getPath());
} else {// only file in zip file, no path
entry = new ZipEntry(file.getName());
}

out.putNextEntry(entry);

// Transfer bytes from the file to the ZIP file
int len;
while ((len = in.read(BUFFER)) > 0) {
out.write(BUFFER, 0, len);
out.flush();
}

// Complete the entry
out.closeEntry();
in.close();
}

// Complete the ZIP file
out.close();
}

/**
* Descompacta o arquivo no local definido por outFilesPath
*
* @param dataIn
*
* @param outFilesPath
* Local onde ficarão os arquivos
* @throws IOException
*/
public static void unpack(DataInputStream dataIn, String outFilesPath)
throws IOException {
ZipInputStream zis = new ZipInputStream(dataIn);
ZipEntry zipEntry = null;
byte[] BUFFER = new byte[BUFFER_SIZE];
String path;
while ((zipEntry = zis.getNextEntry()) != null) {
path = outFilesPath + File.separator + zipEntry.getName();

// if don´t exist, create this path
new File(new File(path).getParent()).mkdirs();

FileOutputStream fileOut = new FileOutputStream(path);
int count;
while ((count = zis.read(BUFFER, 0, BUFFER_SIZE)) != -1) {
fileOut.write(BUFFER, 0, count);
}
fileOut.close();

}
zis.close();
}
}

Nenhum comentário: