android - Android 创建 zip 文件
问题描述
我正在使用这段代码来创建一个 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 文件呢?
解决方案
因为您忘记在文件名上附加基本路径。你的文件名必须是这样的:
String filename = Environment.getExternalStorageDirectory().getPath() + "/" + Helper.Timestamp() + ".zip";
推荐阅读
- excel - 如何匹配 VBA 正则表达式中的所有标点符号(例如其他语言中的 '\p{P}')
- angular - Angular 2 - 将字符串与其他字符串一起翻译为参数
- java - 使用最后创建的文件
- reactjs - 运行流程:安装给出错误
- mysql - 如何删除所有类型为 y 的行,这些行也包含同一个表中类型为 x 的条目?
- symfony - KnpSnappyBundle - wkhtmltopdf:加载 CSS/图像但不加载脚本
- angularjs - AngularJS表单值未显示
- oracle - oracle 包中每个函数/过程调用的所有函数/过程的列表
- django - DJango api 发送刷新和访问令牌
- java - EnumSet / EnumMap 需要泛化 Set / Map