小编DAE*_*EGO的帖子

如果文件不包含有效的 UTF-8,我如何获取文件的内容

我需要获取 a 的内容.jsp,我一直在使用std::fs::read_to_string

if f.file_name() == "entry.jsp" {
    // read_file(f.path().to_str().unwrap());
    println!("{:?}", f.file_name());
    let contents = fs::read_to_string(f.path()).expect("Something went wrong reading the file");
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

“流不包含有效的 UTF-8”

我尝试逐行std::io::BufReader读取文件,但我不知道如何将这些行作为字符串获取。

fn read_file(path: &str) -> std::io::Result<()> {
    let file = File::open(path)?;
    let reader = BufReader::new(file);
    for line in reader.lines() {
        println!("{}", line?);
    }
    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能获得内容String

谢谢。

rust

1
推荐指数
1
解决办法
5451
查看次数

标签 统计

rust ×1