在 Android 开发中,可以使用 Java 标准库中的 `java.util.zip` 包来压缩文件。以下是一个简单的例子:
```java
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;
public class ZipUtils {
public static void zipFile(String sourceFilePath, String zipFilePath) {
try {
File sourceFile = new File(sourceFilePath);
File zipFile = new File(zipFilePath);
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
addFileToZip("", sourceFilePath, zos);
zos.flush();
zos.close();
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void addFileToZip(String path, String srcFilePath, ZipOutputStream zos) throws IOException {
File file = new File(srcFilePath);
if (file.isFile()) {
ZipEntry zipEntry = new ZipEntry(path + file.getName());
zos.putNextEntry(zipEntry);
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
} else {
File[] files = file.listFiles();
if (files != null) {
for (File childFile : files) {
addFileToZip(path + file.getName() + "/", childFile.getAbsolutePath(), zos);
}
}
}
}
}
```
这段代码使用 `ZipOutputStream` 类将单个文件或整个目录压缩成一个 ZIP 文件。你可以像这样使用它:
```java
String sourceFilePath = "/path/to/source/file.txt";
String zipFilePath = "/path/to/output/file.zip";
ZipUtils.zipFile(sourceFilePath, zipFilePath);
```
这个例子假设您要压缩一个名为 `file.txt` 的文件,并将其保存为 `file.zip`。您可以根据需要修改源文件路径和输出 ZIP 文件路径。