我创建了一个目录,其中存储了一些图像。现在,要将其压缩为单个.zip文件,我使用以下代码:
private static void zipDir(String zipFileName, String dir) throws Exception {
File dirObj = new File(dir);
ZipOutputStream out = new ZipOutputStream(newFileOutputStream(zipFileName));
addDir(dirObj, out);
out.close();
}
static void addDir(File dirObj, ZipOutputStream out) throws IOException {
File[] files = dirObj.listFiles();
byte[] tmpBuf = new byte[1024];
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
addDir(files[i], out);
continue;
}
FileInputStream in = new FileInputStream(files[i].getAbsolutePath());
System.out.println(" Adding: " + files[i].getAbsolutePath());
out.putNextEntry(new ZipEntry(files[i].getAbsolutePath()));
int len;
while ((len = in.read(tmpBuf)) > 0) {
out.write(tmpBuf, 0, len);
}
out.closeEntry();
in.close();
}
}
当我运行此代码时,在指定目录中创建一个具有指定名称的.zip文件,但是当我尝试在Android或PC上使用任何软件(winzip等)打开它时,它会显示错误消息:该文件已损坏或无效的zip文件&#34;
任何帮助都将不胜感激。
答案 0 :(得分:0)
我正在考虑删除这个问题。但它代表了一个相当有趣的读物。在创建.zip文件时,我指定了与我想要压缩的目录相同的目录。这导致无限循环。更改.zip目录可以解决问题。
答案 1 :(得分:0)
我是这样的意思:
private static void zipDir(String zipFileName, String dir) throws Exception {
List<String> files = buildFileList(dir, "");
ZipOutputStream out = new ZipOutputStream(newFileOutputStream(zipFileName));
zipFiles(files, out);
out.close();
}
static List<String> buildFileList(String path, String filter) {
List<String> lstFile = new ArrayList<String>();
File[] files = new File(path).listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
File f = files[i];
if (f.isFile()) {
if (filter.length() == 0 || f.getName().matches(filter))
lstFile.add(f.getAbsolutePath());
} else if (f.isDirectory() && f.getPath().indexOf("/.") == -1)
lstFile.addAll(getFilePaths(f.getAbsolutePath(), filter));
}
}
return lstFile;
}
static void zipFiles(List<String> files, ZipOutputStream out) throws IOException {
byte[] tmpBuf = new byte[1024];
for (String file : files) {
if (new File(file).isDirectory()) {
continue;
}
FileInputStream in = new FileInputStream(file);
System.out.println(" Adding: " + file);
out.putNextEntry(new ZipEntry(file));
int len;
while ((len = in.read(tmpBuf)) > 0) {
out.write(tmpBuf, 0, len);
}
out.closeEntry();
in.close();
}
}