在Android中,可以使用以下步骤以编程方式压缩文件:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
private void compressFile(String sourceFilePath, String destinationFilePath) throws IOException {
File sourceFile = new File(sourceFilePath);
FileOutputStream fos = new FileOutputStream(destinationFilePath);
ZipOutputStream zos = new ZipOutputStream(fos);
compressFileRecursive(sourceFile, sourceFile.getName(), zos);
zos.close();
fos.close();
}
private void compressFileRecursive(File file, String fileName, ZipOutputStream zos) throws IOException {
if (file.isHidden()) {
return;
}
if (file.isDirectory()) {
if (fileName.endsWith("/")) {
zos.putNextEntry(new ZipEntry(fileName));
zos.closeEntry();
} else {
zos.putNextEntry(new ZipEntry(fileName + "/"));
zos.closeEntry();
}
File[] children = file.listFiles();
for (File childFile : children) {
compressFileRecursive(childFile, fileName + "/" + childFile.getName(), zos);
}
return;
}
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
fis.close();
}
String sourceFilePath = "/path/to/source/file";
String destinationFilePath = "/path/to/destination/file.zip";
compressFile(sourceFilePath, destinationFilePath);
这样,你就可以在Android中以编程方式压缩文件了。
请注意,以上代码仅为示例,实际使用时需要根据具体需求进行适当修改和错误处理。此外,压缩文件可能需要一定的时间和资源,因此在处理大文件或大量文件时,建议在后台线程中执行压缩操作,以避免阻塞主线程。
领取专属 10元无门槛券
手把手带您无忧上云