gpt4 book ai didi

android - 在android上压缩/压缩一个充满文件的文件夹

转载 作者:IT王子 更新时间:2023-10-28 23:27:46 26 4
gpt4 key购买 nike

我需要压缩一个“项目”文件夹以允许用户通过电子邮件共享项目。我找到了一个将多个文件压缩到一个 zip 中的类,但我需要将文件夹结构保留在我的 zip 中。有没有办法在android上实现这一点?提前致谢。

最佳答案

这段代码应该可以解决问题。

注意:您必须通过将 WRITE_EXTERNAL_STORAGE 权限添加到 manifest.xml 文件来为您的应用添加文件写入权限。

/*
*
* Zips a file at a location and places the resulting zip file at the toLocation
* Example: zipFileAtPath("downloads/myfolder", "downloads/myFolder.zip");
*/

public boolean zipFileAtPath(String sourcePath, String toLocation) {
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));
entry.setTime(sourceFile.lastModified()); // to keep modification time after unzipping
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;
}

/*
*
* Zips a subfolder
*
*/

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);
FileInputStream fi = new FileInputStream(unmodifiedFilePath);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(relativePath);
entry.setTime(file.lastModified()); // to keep modification time after unzipping
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
}
}

/*
* gets the last path component
*
* Example: getLastPathComponent("downloads/example/fileToZip");
* Result: "fileToZip"
*/
public String getLastPathComponent(String filePath) {
String[] segments = filePath.split("/");
if (segments.length == 0)
return "";
String lastPathComponent = segments[segments.length - 1];
return lastPathComponent;
}

关于android - 在android上压缩/压缩一个充满文件的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6683600/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com