package cologne.eck.tools;
import java.awt.Window;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.ResourceBundle;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.swing.JOptionPane;
public class ZipStuff {
private static final int BUFFER_SIZE = 1024 * 1024;//8192;
/**
* If addFilesToZip failed, error message contains the
* description of the error
*/
private static String errorMessage;
/**
* Creates a zip file containing all files of the given folder, but not
* sub-directories and files inside of sub-directories
*
* @param folderName the directory name which contains the files to archive
* @param zipName name of the zip file
*
* @return null if the function performs successfully,
* an error message if the function fails
*/
public static String zipFolder(String folderName, String zipName, Window window, ResourceBundle bundle) {
File folder = new File(folderName);
if (! folder.exists()) {
System.err.println("ZipStuff (zipFolder): directory to zip does not exist");
return "ZipStuff (zipFolder): directory to zip does not exist";
}
if (! folder.canRead()){
System.err.println("ZipStuff (zipFolder): can not read directory to zip");
return "ZipStuff (zipFolder): can not read directory to zip";
}
if (! folder.isDirectory()){
System.err.println("ZipStuff (zipFolder): file to zip is not directory");
return "ZipStuff (zipFolder): file to zip is not directory";
}
String path = folderName.substring(0, folderName.lastIndexOf(File.separator));
String zipFileName = path + File.separator + zipName + ".zip";
if ( new File(zipFileName).exists() ){
int overwrite = JOptionPane.showConfirmDialog(
window,
bundle.getString("overwrite_existing_file"),
bundle.getString("warning"),
JOptionPane.OK_CANCEL_OPTION);
if (! (overwrite == JOptionPane.OK_OPTION)){
return bundle.getString("cancel") + ":\n " +zipFileName;
}
}
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(zipFileName);
// target zip output stream
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
// compress:
out.setMethod(ZipOutputStream.DEFLATED);
byte data[] = new byte[BUFFER_SIZE];
// get a list of files from directory
String files[] = folder.list();
for (int i=0; i<files.length; i++) {
//System.out.println("Adding: "+files[i]);
FileInputStream fi = new FileInputStream(folderName + File.separator + files[i]);
origin = new BufferedInputStream(fi, BUFFER_SIZE);
ZipEntry entry = new ZipEntry(files[i]);
out.putNextEntry(entry);
int count;
while((count = origin.read(data, 0,
BUFFER_SIZE)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch (FileNotFoundException e) {
//e.printStackTrace();
System.err.println("ZipStuff (zipFolder): " + e.toString() + ", " + e.getMessage());
return e.toString() + ", " + e.getMessage();
} catch (IOException e) {
//e.printStackTrace();
System.err.println("ZipStuff (zipFolder): " + e.toString() + ", " + e.getMessage());
return e.toString() + ", " + e.getMessage();
} catch (Exception e) {
//e.printStackTrace();
System.err.println("ZipStuff (zipFolder): " + e.toString() + ", " + e.getMessage());
return e.toString() + ", " + e.getMessage();
}
return null;
}
/**
* Extract one file from the given zip file
*
* @param fileName name of the file to extract.
* @param zipName name of the zip file which contains the
* file to extract
*
* @return the content of the extracted file as an
* array of bytes
*/
public static byte[] getFileFromZipFile(String fileName, String zipName) {
errorMessage = null;
File zipFile = new File(zipName);
if (! zipFile.exists()) {
System.err.println("ZipStuff (getFileFromZip): zip file does not exist");
errorMessage = "ZipStuff (getFileFromZip): zip file does not exist";
return null;
}
if (! zipFile.canRead()){
System.err.println("ZipStuff (getFileFromZip): can not read zip file");
errorMessage = "ZipStuff (getFileFromZip): can not read zip file";
return null;
}
if (zipFile.isDirectory()){
System.err.println("ZipStuff (getFileFromZip): zip file is directory");
errorMessage = "ZipStuff (getFileFromZip): zip file is directory";
return null;
}
FileInputStream fis = null;
try {
fis = new FileInputStream(zipFile);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
while((entry = zis.getNextEntry()) != null) {
//System.out.println("Extracting: " +entry);
if (entry.getName().endsWith(fileName)){
//FileOutputStream fos = new FileOutputStream(entry.getName());
ByteArrayOutputStream buffOut = new ByteArrayOutputStream(BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = 0;
while ((bytesRead = zis.read(buffer)) != -1) {
buffOut.write(buffer, 0, bytesRead);
}
return (buffOut == null) ? null : buffOut.toByteArray();
}
}
fis.close();
} catch (FileNotFoundException e) {
System.err.println("ZipStuff (getFileFromZip): " + e.toString() + ", " + e.getMessage());
errorMessage = e.toString() + ", " + e.getMessage();
//e.printStackTrace();
} catch (IOException e) {
System.err.println("ZipStuff (getFileFromZip): " + e.toString() + ", " + e.getMessage());
errorMessage = e.toString() + ", " + e.getMessage();
//e.printStackTrace();
} catch (Exception e) {
System.err.println("ZipStuff (getFileFromZip): " + e.toString() + ", " + e.getMessage());
errorMessage = e.toString() + ", " + e.getMessage();
//e.printStackTrace();
}
return null;
}
/**
* Add one file to a given zip file.
* 1. The original zip file is unzipped,
* 2. the entries are added to a temporary zip file called tmp.zip,
* 3. the file is appended to the temporary zip file,
* 4. the given original zip file is deleted
* 5. and the temporary zip file is renamed to the original zip file.
*
*
* @param fileName
* @param oldZipName
*
* @return an error message if the operation failed, null otherwise
*/
public static String addFileToZip(String fileName, String oldZipName) {
String errorMessage = null;
// read war.zip and write to append.zip
ZipFile zipFile;
try {
zipFile = new ZipFile(oldZipName);
ZipOutputStream zipStream = new ZipOutputStream(new FileOutputStream("test/tmp.zip"));
// copy files from existing zip
Enumeration<? extends ZipEntry> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
byte[] buffer = new byte[BUFFER_SIZE];
// System.out.println( entry.getName());
zipStream.putNextEntry(entry);
if (!entry.isDirectory()) {
InputStream input = zipFile.getInputStream(entry);
int bytesRead;
while ((bytesRead = input.read(buffer))!= -1) {
zipStream.write(buffer, 0, bytesRead);
}
}
}
// append file
ZipEntry entry = new ZipEntry(fileName);
zipStream.putNextEntry(entry);
zipStream.write(ReadResources.readExternFile("test" + File.separator + entry.getName()));
zipStream.closeEntry();
// close
zipFile.close();
zipStream.close();
} catch (FileNotFoundException e) {
System.err.println("ZipStuff (addFileToZip): " + e.toString() + ", " + e.getMessage());
errorMessage = e.toString() + ", " + e.getMessage();
//e.printStackTrace();
} catch (IOException e) {
System.err.println("ZipStuff (addFileToZip): " + e.toString() + ", " + e.getMessage());
errorMessage = e.toString() + ", " + e.getMessage();
//e.printStackTrace();
} catch (Exception e) {
System.err.println("ZipStuff (addFileToZip): " + e.toString() + ", " + e.getMessage());
errorMessage = e.toString() + ", " + e.getMessage();
//e.printStackTrace();
}
try {
File oldFile = new File(oldZipName);
oldFile.delete();
File tmpFile = new File("test/tmp.zip");
tmpFile.renameTo(oldFile);
} catch (Exception e) {
errorMessage = "Rename file failed: " + e.toString() + ", " + e.getMessage();
}
return errorMessage;
}
/* public static void main(String[] args) {
ZipStuff.zipFolder("test/testFolder", "test/test.zip");
byte[] content = ZipStuff.getFileFromZipFile("P1010019.JPG", "test/test.zip");
WriteResources.write(content, "newFile", "test");
ZipStuff.addFileToZip("newFile", "test/test.zip");
}*/
/**
* If the function addFileToZip() failed,
* the error message contains a description
* of the error
*
* @return the errorMessage
*/
public static String getErrorMessage() {
return errorMessage;
}
}