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

8
我有一个base64图像,并从中得到了Vec<u8>,然后将它们写入文件。这是我的代码:
let file_contents_base64: Vec<u8> = image_base64::from_base64(
    String::from(&file_contents_string_vec[0])
);

我想把变量file_contents_base64写入一个文件。
2个回答

13
除了fs::write之外,还有一般化的解决方案,适用于实现Write特质的所有内容,通过使用write_all方法:
use std::io::Write; // bring trait into scope
use std::fs;

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

file.write_all(&file_contents_base64);

1
在回答问题之前,请查找重复问题并投票关闭。 - Shepmaster
3
OpenOptions是什么?OpenOptions是一个用于管理和控制数据库连接选项的接口。它可以让开发者自定义数据库连接行为,例如设置超时时间、打开多个连接等。使用OpenOptions接口可以使应用程序更加灵活和可靠。 - decodebytes

8
你使用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();

1
在回答问题之前,请查找重复问题并投票关闭。 - Shepmaster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接