【问题标题】:Android Create zip fileAndroid 创建 zip 文件
【发布时间】:2019-12-31 03:56:14
【问题描述】:

我正在使用这段代码来创建一个 zip 文件:

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();
}

辅助函数:

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();
    }
}

但是out.write(data, 0, len); 似乎有问题,因为在这个函数调用中有一个NullPointerException。我相信这是因为我的CreateZipOutputStream 抛出了FileNotFoundException

那么我应该如何正确地创建一个 zip 文件呢?

【问题讨论】:

    标签: android zipoutputstream


    【解决方案1】:

    因为您忘记在文件名上附加基本路径。你的文件名必须是这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 2012-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多