sevenz-rust2的实现方法及使用示例
“请问sevenz-rust2的具体实现方法是怎样的?能否提供一个简单的使用示例?我在尝试使用时遇到了一些问题,希望能得到更详细的指导。”
2 回复
SevenZ-Rust2 是基于 Rust 语言开发的 7z 压缩格式处理库,提供高性能的压缩与解压功能。以下是实现方法及使用示例:
实现方法
-
依赖添加
在Cargo.toml
中添加依赖:[dependencies] sevenz-rust = "0.4"
-
核心功能
- 压缩:支持目录/文件压缩为
.7z
。 - 解压:提取
.7z
文件内容,支持密码保护归档。 - 基于
sevenz-rust
库的异步或同步接口(具体版本特性需确认)。
- 压缩:支持目录/文件压缩为
使用示例
1. 解压文件
use sevenz_rust::decompress_file;
fn main() -> Result<(), Box<dyn std::error::Error>> {
decompress_file("archive.7z", "./output/", /* 密码: */ None)?;
Ok(())
}
2. 压缩文件/目录
use sevenz_rust::compress_to_path;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let paths = vec!["file1.txt", "dir/"];
compress_to_path(&paths, "output.7z")?;
Ok(())
}
3. 设置密码压缩
use sevenz_rust::{SevenZArchiveOptions, compress_to_path_with_options};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let options = SevenZArchiveOptions {
password: Some("mypassword".into()),
..Default::default()
};
compress_to_path_with_options(&["data.txt"], "encrypted.7z", options)?;
Ok(())
}
注意事项
- 确认库版本(如
sevenz-rust
或sevenz-rust2
),API 可能随版本更新变化。 - 解压加密文件时需在参数中传递密码。
- 支持跨平台(Windows/Linux/macOS)。
通过上述代码即可快速集成 7z 压缩功能到 Rust 项目中。