利用线程池多线程解压文件提高解压效率

该博客介绍了一种通过线程池实现大文件解压效率提升的方法。在Java中,通过创建固定大小的线程池,将ZipEntry元素分配给任务并执行,从而并行解压文件。每个任务负责读取ZipEntry对应的输入流,并将其写入到目标文件。实测证明,这种方法能有效加快解压过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在解压大文件时,利用线程池多线程解压文件提高解压效率,参考网络资源,实测有效:

private void decompress(String srcPath, String destPath) throws IOException {

	long start = System.currentTimeMillis();
	this.zipFile = new ZipFile(srcPath);
	this.destPath = destPath;

	Enumeration<? extends ZipEntry> entries = zipFile.entries();

	ExecutorService threadPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
	// Log.i("ERIC", "// decompress()//==========entries.hasMoreElements()= " + entries.hasMoreElements());
	while (entries.hasMoreElements()) {
		ZipEntry zipEntry = entries.nextElement();

		if (zipEntry.isDirectory()) {
		continue;
		}

		threadPool.execute(new FileWritingTask(zipEntry));
	}
	Log.i("ERIC", "// decompress()//==========threadPool.shutdown()========== " );
	threadPool.shutdown();
	SystemProperties.set("persist.elmo.copyfiles", "false");
	try {
		threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
	zipFile.close();

	long end = System.currentTimeMillis();
	// Log.i("ERIC","解压完成,所用时间为:" + (end - start) + "ms");

}



private class FileWritingTask implements Runnable {

	private ZipEntry zipEntry;

	FileWritingTask(ZipEntry zipEntry) {
		this.zipEntry = zipEntry;
	}

	@Override
	public void run() {
		File file = new File(destPath + File.separator + zipEntry.getName());
		Log.i("ERIC", "// FileWritingTask file= " + file.getAbsolutePath());

		File parentFile = file.getParentFile();
		if (!parentFile.exists()) {
			parentFile.mkdirs();
		}
		try (
			InputStream inputStream = zipFile.getInputStream(this.zipEntry);
			OutputStream outputStream = new FileOutputStream(file);
		) {
			
			int read;
			byte[] bytes = new byte[inputStream.available()];
			while ((read = inputStream.read(bytes)) != -1) {
			outputStream.write(bytes, 0, read);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值