Zipfile has to be situated in the data-folder, and unpackFileFromZip will write to the data-folder.
usage:
PImage image = loadImageFromZip("zipname.zip","image.gif");
String text = loadStringFromZip("zipname.zip","helloworld.txt");
byte[] bytes = loadBytesFromZip("zipname.zip","whatever.duh");
Quote:
String unpackFileFromZip(String zipname, String fname) // indepentent (meaning everything else works without this)
{
if(online) return "only offline, or with a signed applet";
byte[] bytes = loadBytesFromZip(zipname,fname);
File output = new File(sketchPath("data\\"+fname));
try {
OutputStream out = new FileOutputStream(output.getAbsolutePath());
out.write(bytes,0,bytes.length);
out.close();
}catch(Exception e){
return e.toString();
}
return output.getAbsolutePath();
}
String loadStringFromZip(String zipname, String fname) // indepentent
{
byte[] ret = loadBytesFromZip(zipname,fname);
if(ret == null) return null;
return new String(ret);
}
PImage loadImageFromZip(String zipname, String fname) // indepentent
{
if(!(fname.toLowerCase().endsWith(".gif") || fname.toLowerCase().endsWith(".jpg"))){
println("Format not accepted: "+fname);
return null;
}
byte[] ret = loadBytesFromZip(zipname,fname);
if(ret == null) return null;
return loadImage(ret);
}
PImage loadImage(byte[] bytes) // used by loadImageFromZip()
{
Image img = Toolkit.getDefaultToolkit().createImage(bytes);
MediaTracker t = new MediaTracker(this);
t.addImage(img, 0);
try {
t.waitForAll();
} catch (Exception e) {
println(e);
}
return new PImage(img);
}
byte[] loadBytesFromZip(String zipname, String fname) // used by loadStringFromZip, loadImageFromZip and unpackFileFromZip
{
try {
// Open the ZIP file
File inFilename = new File(sketchPath("data\\"+zipname));
ZipInputStream in = new ZipInputStream(new FileInputStream(inFilename.getAbsolutePath()));
// Get the entry that matches
ZipEntry entry = in.getNextEntry();
while(!entry.getName().toLowerCase().equals(fname.toLowerCase())){
entry = in.getNextEntry();
}
if(!entry.getName().toLowerCase().equals(fname.toLowerCase())){
println("No such file: "+fname);
return null;
}
// Transfer bytes from the ZIP file to the bytearrayoutputstream
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
bout.write(buf,0,len);
}
// Close the stream
byte[] ret = bout.toByteArray();
in.close();
bout.close();
return ret;
} catch (IOException e) {
println(e);
}
return null;
}
-seltar