如何从 Vec<u8> 写入文件?

问题描述

我有一个 base64 图像并从中获取 Vec<u8> 并将它们写入文件。 这是我的代码:

let file_contents_base64: Vec<u8> = image_base64::from_base64(
    String::from(&file_contents_string_vec[0])
);

我想将 file_contents_base64 变量写入文件。

解决方法

您使用 image-base64 crate 的事实似乎与该问题无关。考虑到您只想将 Vec<u8> 写入文件,那么您可以使用例如fs::write()

use std::fs;
use std::path::Path;

let file_contents_base64: Vec<u8> = ...;
let path: &Path = ...;

fs::write(path,file_contents_base64).unwrap();
,

除了 fs::write 之外,通过使用 Write,还有一个适用于所有实现 write_all trait 的通用解决方案:

use std::io::Write; // bring trait into scope
use std::fs;

// ... later in code
let file = OpenOptions::new()
    .write(true)
    // either use ? or unwrap since it returns a Result
    .open("/path/to/file")?;

file.write_all(&file_contents_base64);

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...