如何使用zip/rc_zip库读取zip压缩包内可变路径下的特定文件
基于zip库的实现方案
实现思路
zip库没有提供直接查询指定目录下子条目的API,我们可以直接遍历压缩包内的所有条目,通过路径规则匹配到目标文件。你的场景下info目录下只有一个子文件夹,所以匹配info/*/info.json规则的路径只会有一个,直接读取即可。
完整代码
use std::fs::File; use std::io::{BufReader, Read}; use zip::ZipArchive; fn main() { // 替换为你的压缩包实际路径 let file_path = file.to_str().unwrap(); let file = File::open(file_path).unwrap(); let reader = BufReader::new(file); let mut archive = ZipArchive::new(reader).unwrap(); // 遍历所有归档条目查找目标文件 let mut target_file = None; for i in 0..archive.len() { let entry = archive.by_index(i).unwrap(); let entry_path = entry.name(); // 匹配路径规则:以info/开头,以/info.json结尾 if entry_path.starts_with("info/") && entry_path.ends_with("/info.json") { target_file = Some(entry); break; } } // 读取info.json内容 let mut json_content = String::new(); target_file.unwrap().read_to_string(&mut json_content).unwrap(); // 后续可自行解析json_content }
可选严格层级校验
如果需要避免嵌套层级异常的误匹配,可以增加路径拆分校验逻辑:
let path_segments: Vec<&str> = entry_path.split('/').collect(); // 校验路径层级刚好是3级:info/[随机字符串]/info.json if path_segments.len() == 3 && path_segments[0] == "info" && path_segments[2] == "info.json" { target_file = Some(entry); break; }
基于rc_zip库的实现说明
rc_zip的实现逻辑完全一致,仅API调用方式有细微差别,同样遍历归档内的所有条目,匹配上述路径规则后读取内容即可。
注意:压缩包内的路径统一使用
/作为分隔符,不需要适配不同操作系统的本地路径格式。
内容的提问来源于stack exchange,提问作者RainHunter
相关产品推荐
相关产品推荐

