0

I am using this piece of code to create a zip file:

String filename = Helper.Timestamp() + ".zip";
ZipOutputStream out = Helper.CreateZipOutputStream(filename);
Helper.AddZipFolder(out, Helper.ImageFolder);
Helper.AddZipFile(out, new File(Settings.FILENAME));
try {
    out.close();
} catch (IOException e) {
    e.printStackTrace();
}

Helper functions:

public static String Timestamp() { return new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); }
public static ZipOutputStream CreateZipOutputStream(String filename){
    FileOutputStream dest = null;
    try {
        dest = new FileOutputStream(filename);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return new ZipOutputStream(new BufferedOutputStream(dest));
}
public static void AddZipFolder(ZipOutputStream out, File folder){
    for (File file: folder.listFiles()){
        Helper.AddZipFile(out, file, folder.getName() + File.separator + file.getName());
    }
}
public static void AddZipFile(ZipOutputStream out, File file){
    AddZipFile(out, file, file.getName());
}
public static void AddZipFile(ZipOutputStream out, File file, String path){
    byte[] data = new byte[1024];
    FileInputStream in;
    try {
        in = new FileInputStream(file);
    } catch (FileNotFoundException e) {
        return;
    }
    try {
        out.putNextEntry(new ZipEntry(path));
        int len;
        while ((len = in.read(data)) > 0)
            out.write(data, 0, len);
        out.closeEntry();
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

However there seems to be something wrong with the out.write(data, 0, len); because there is a NullPointerException inside this function call. I believe this is due to the fact that my CreateZipOutputStream throws a FileNotFoundException.

So how should I properly create a zip file?

Seaky
  • 239
  • 2
  • 13

1 Answers1

1

Because you forget to append base path on your filename. your filename must be like:

String filename = Environment.getExternalStorageDirectory().getPath() + "/" + Helper.Timestamp() + ".zip";