如何使用Java在Android编程中实现多线程处理,将指定文件夹内的所有.jpg图片文件批量压缩,并将其保存到另一个指定位置?请提供相应的代码示例,并确保包含详细的注释解释每个步骤和关键部分。
时间: 2024-11-12 17:38:03 浏览: 13
在Android编程中,我们可以使用Java的`ExecutorService`和`ThreadPoolExecutor`来创建并管理线程池,同时配合`java.nio.file`包下的API来操作文件。以下是使用Java多线程处理文件批量压缩的简单示例:
```java
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
// 使用ExecutorService处理任务
public class ImageCompressor {
private static final int THREAD_POOL_SIZE = 4; // 线程池大小
public static void main(String[] args) {
// 指定源文件夹路径和目标压缩文件路径
String sourceDirPath = "/path/to/source/directory";
String targetZipPath = "/path/to/target/archive.zip";
try {
// 创建线程池
ExecutorService executor = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
// 获取源目录下的所有jpg文件
List<File> imageFiles = getJpgFiles(sourceDirPath);
// 提交压缩任务到线程池
for (File file : imageFiles) {
executor.submit(new CompressImageTask(file, targetZipPath));
}
// 关闭线程池
executor.shutdown();
// 当所有任务完成时打印一条消息
System.out.println("All images compressed successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
// 辅助方法:获取指定目录下的所有.jpg文件
private static List<File> getJpgFiles(String directoryPath) throws IOException {
File dir = new File(directoryPath);
if (!dir.exists() || !dir.isDirectory()) {
throw new IllegalArgumentException("Invalid source directory");
}
ArrayList<File> jpgFiles = new ArrayList<>();
Files.walk(dir.toPath())
.filter(path -> path.toString().endsWith(".jpg"))
.map(Path::toFile)
.forEach(jpgFiles::add);
return jpgFiles;
}
// 定义压缩图片的任务类
private static class CompressImageTask implements Runnable {
private final File imageFile;
private final String zipFilePath;
public CompressImageTask(File imageFile, String zipFilePath) {
this.imageFile = imageFile;
this.zipFilePath = zipFilePath;
}
@Override
public void run() {
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
// 添加zip入口
ZipEntry entry = new ZipEntry(imageFile.getName());
zos.putNextEntry(entry);
// 读取并写入文件内容
byte[] buffer = new byte[1024];
FileInputStream fis = new FileInputStream(imageFile);
int length;
while ((length = fis.read(buffer)) != -1) {
zos.write(buffer, 0, length);
}
// 清理流
zos.closeEntry();
fis.close();
} catch (IOException e) {
System.err.println("Failed to compress " + imageFile.getAbsolutePath() + ": " + e.getMessage());
}
}
}
}
阅读全文