我是使用 Kotlin 语言开发 Android 应用程序的初学者。我已经编写了一些简单的应用程序,现在我计划编写一个应用程序,允许用户以自定义压缩率(在 EditText 中输入)压缩存储在内部存储器中的多个图像(JPG 格式),然后自动压缩将所有这些图像压缩到一个 zip 文件中,以便轻松附加到电子邮件或共享。压缩后的图像文件将保存到自定义文件夹中。由于我缺乏经验,我希望您能指导我从哪里开始。非常感谢。
我尝试按照互联网上的一些说明进行操作,但是当我运行它们时,我收到一条错误消息,或者该程序只允许我一次压缩一张图像。
您可以尝试下面的代码片段来压缩多个文件。
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ZipHelper {
public static void compressFiles(String zipFilePath, String[] sourceFiles) throws IOException {
try (ZipOutputStream zipOutputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFilePath)))) {
byte[] buffer = new byte[1024];
for (String filePath : sourceFiles) {
try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(filePath))) {
ZipEntry zipEntry = new ZipEntry(getFileNameFromPath(filePath));
zipOutputStream.putNextEntry(zipEntry);
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
zipOutputStream.write(buffer, 0, bytesRead);
}
zipOutputStream.closeEntry();
}
}
}
}
private static String getFileNameFromPath(String filePath) {
// Extract the file name from the full path
int lastSeparator = filePath.lastIndexOf("/");
return (lastSeparator == -1) ? filePath : filePath.substring(lastSeparator + 1);
}
}
以下是使用上述方法的示例代码。
String[] filesToCompress = new String[]{"/path/to/file1.txt", "/path/to/file2.txt", "/path/to/file3.png"};
String zipFilePath = "/path/to/archive.zip";
try {
ZipHelper.compressFiles(zipFilePath, filesToCompress);
// Compression completed successfully
} catch (IOException e) {
e.printStackTrace();
// Handle compression error
}
希望有帮助。 安基特
感谢@Ankit Dubey,这是我的 createZipFile 函数代码,但它不起作用。错误消息是“打开失败:EPERM(不允许操作)”,即使我已授予应用程序完整的内存读/写权限。
private val zipLock = Object()
private suspend fun createZipFile(imageFiles: List<File>) {
withContext(Dispatchers.IO) {
try {
synchronized(zipLock) {
val currentTime = System.currentTimeMillis()
zipFileName = "Images_${currentTime}.zip"
val zipFilePath = File(getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), zipFileName)
ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFilePath))).use { zipOut ->
for (imageFile in imageFiles) {
val zipEntry = ZipEntry(imageFile.name)
zipOut.putNextEntry(zipEntry)
val input = BufferedInputStream(FileInputStream(imageFile))
val data = ByteArray(2048)
var count: Int
while (input.read(data, 0, 2048).also { count = it } != -1) {
zipOut.write(data, 0, count)
}
input.close()
zipOut.closeEntry()
}
}
}
withContext(Dispatchers.Main) {
Toast.makeText(
this@MainActivity,
"Files have been successfully packed: ${zipFileName}",
Toast.LENGTH_SHORT
).show()
}
} catch (e: Exception) {
e.printStackTrace()
withContext(Dispatchers.Main) {
Toast.makeText(this@MainActivity, "Files have been unsuccessfully packed: ${e.message}", Toast.LENGTH_SHORT).show()
}
}
}
}