Android ZIP文件夹

时间:2014-10-08 22:58:13

标签: android zip

我将此代码用于ZIP文件夹,包括内部文件夹:

public boolean zipFileAtPath(String sourcePath, String toLocation) {
// ArrayList<String> contentList = new ArrayList<String>();
final int BUFFER = 2048;
File sourceFile = new File(sourcePath);
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(toLocation);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
        dest));
if (sourceFile.isDirectory()) {
    zipSubFolder(out, sourceFile, sourceFile.getParent().length());
} else {
    byte data[] = new byte[BUFFER];
    FileInputStream fi = new FileInputStream(sourcePath);
    origin = new BufferedInputStream(fi, BUFFER);
    ZipEntry entry = new ZipEntry(getLastPathComponent(sourcePath));
    out.putNextEntry(entry);
    int count;
    while ((count = origin.read(data, 0, BUFFER)) != -1) {
        out.write(data, 0, count);
    }
}
out.close();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}

private void zipSubFolder(ZipOutputStream out, File folder,
int basePathLength) throws IOException {
final int BUFFER = 2048;
File[] fileList = folder.listFiles();
BufferedInputStream origin = null;
for (File file : fileList) {
if (file.isDirectory()) {
    zipSubFolder(out, file, basePathLength);
} else {
    byte data[] = new byte[BUFFER];
    String unmodifiedFilePath = file.getPath();
    String relativePath = unmodifiedFilePath
            .substring(basePathLength);
    Log.i("ZIP SUBFOLDER", "Relative Path : " + relativePath);
    FileInputStream fi = new FileInputStream(unmodifiedFilePath);
    origin = new BufferedInputStream(fi, BUFFER);
    ZipEntry entry = new ZipEntry(relativePath);
    out.putNextEntry(entry);
    int count;
    while ((count = origin.read(data, 0, BUFFER)) != -1) {
        out.write(data, 0, count);
    }
    origin.close();
 }
}
}

public String getLastPathComponent(String filePath) {
String[] segments = filePath.split("/");
String lastPathComponent = segments[segments.length - 1];
return lastPathComponent;
}

当文件夹如下所示时,它可以正常工作:

  • 文件夹
    • txt file
    • jpg文件
    • txt file

文件夹如下所示也可以正常工作:

  • 文件夹
    • txt file
    • 文件夹
      • txt file
    • txt file

然而在这种情况下:

  • 文件夹
    • txt file
    • 文件夹
      • txt file
      • jpg文件
    • txt file

当ZIP文件不断增加时,它会启动无限循环。

我注意到,它发生的原因是这个循环:

 private void zipSubFolder(ZipOutputStream out, File folder,
 int basePathLength) throws IOException {
 .....

 while ((count = origin.read(data, 0, BUFFER)) != -1) {
        out.write(data, 0, count);
    }
 ....
 }
如上所述,

并不会停止。

为什么会发生这种情况的任何想法?谢谢)

1 个答案:

答案 0 :(得分:0)

这是解决方案。

我将ZIP文件保存在同一个文件夹中,即拉链。所以它开始压缩ZIP文件本身,一次又一次地保存新的ZIP文件。

不确定,如果它清楚,但无论如何,请注意保存ZIP文件的位置。