我正在做一个Android项目。我需要压缩SD卡的完整文件夹结构。 如果文件夹中存在任何文件,代码可以压缩文件夹,否则跳过该文件夹。
我的文件夹结构如:mnt / sdcard / Movies / Telugu / Files。
mnt / sdcard / Movies / English - >英文是空文件夹
我没有在输出zip文件中看到英文文件夹。
我的代码:
public void zip() {
try {
// create a ZipOutputStream to zip the data to
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(
_zipFile));
zipDir(folderPath, zos);
// close the stream
zos.close();
} catch (Exception e) {
// handle exception
}
}
public void zipDir(String dir2zip, ZipOutputStream zos) {
try {
File zipDir = new File(dir2zip);
// get a listing of the directory content
String[] dirList = zipDir.list();
byte[] readBuffer = new byte[2156];
int bytesIn = 0;
// loop through dirList, and zip the files
for (int i = 0; i < dirList.length; i++) {
File f = new File(zipDir, dirList[i]);
if (f.isDirectory()) {
// if the File object is a directory, call this
// function again to add its content recursively
String filePath = f.getPath();
zipDir(filePath, zos);
// loop again
continue;
}
// if we reached here, the File object f was not a directory
// create a FileInputStream on top of f
FileInputStream fis = new FileInputStream(f);
// create a new zip entry
ZipEntry anEntry = new ZipEntry(f.getPath());
// place the zip entry in the ZipOutputStream object
zos.putNextEntry(anEntry);
// now write the content of the file to the ZipOutputStream
while ((bytesIn = fis.read(readBuffer)) != -1) {
zos.write(readBuffer, 0, bytesIn);
}
// close the Stream
fis.close();
}
} catch (Exception e) {
e.printStackTrace();
// handle exception
}
}
请帮助..
答案 0 :(得分:0)
您基本上不会为您的目录创建zipentry。
在if (f.isDirectory()) {}
部分,添加以下内容:
zos.putNextEntry(new ZipEntry(filePath));
您也可以将其放在方法的开头,也可以包含根目录。