Save data to ZIP file in Java app for OS X, Windows and Android platforms
Question: In an Eclipse JAVA project I have to save data to a zip file to reduce disk (memory) usage. I am sending my code. It does not run on Windows 7 professional laptop. Do you have a sample code that runs on both OS X and Windows?
Answer: There are several good solutions on the Net (google or bing for it). Look for file access rights or misspelled file name when your code does not work. From within your Java applications you can execute data compression and decompression conveniently by using the java.util.zip package. A sample code is here:
visit Java’s page from here.
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public boolean saveToZip(String filepath, byte[] data){
boolean success = false;
try{
if( filepath!=null && !filepath.isEmpty() && data != null ){
//Construct the BufferedOutputStream object
BufferedOutputStream bufferedOutput = new BufferedOutputStream(new FileOutputStream(filepath));
// Construct ZipOutputStream object
ZipOutputStream zip = new ZipOutputStream(bufferedOutput);
zip.setMethod(ZipOutputStream.DEFLATED);
zip.setLevel(Deflater.BEST_COMPRESSION);
// Create an entry for our data:
zip.putNextEntry( new ZipEntry("data") );
// Write to file
zip.write(data);
// Close file
zip.close();
success = true;
}
}catch (Exception ex){
System.out.println("saveToZip exception (" + ex.getMessage() + ") error. Path? Access rights?");
}
return success;
}