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

DAE*_*EGO 1 rust

我需要获取 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

谢谢。

Jmb*_*Jmb 6

Rust 中的字符串需要为 UTF-8,因此您无法获得String. 您可以做的是将文件读取为字节(例如。read_to_end),然后将字节转换为字符串from_utf8_lossy

\n\n
if f.file_name() == "entry.jsp" {\n    // read_file(f.path().to_str().unwrap());\n    println!("{:?}", f.file_name());\n    let file = File::open(path)?;\n    let mut buf = vec![];\n    file.read_to_end (&mut buf)?;\n    let contents = String::from_utf8_lossy (&buf);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

但请注意,正如名称中的“有损”部分所示,您获得的字符串将与文件的内容不同:

\n\n
\n

然而,并非所有字节片都是有效的字符串:字符串必须是有效的 UTF-8。在此转换期间,from_utf8_lossy()将用 替换任何无效的 UTF-8 序列U+FFFD REPLACEMENT CHARACTER,如下所示: \xef\xbf\xbd

\n
\n\n

如果您知道您的输入使用除 UTF-8 之外的某些有效字符编码,还有其他解决方案:

\n\n\n

  • [encoding_rs](https://crates.io/crates/encoding_rs) 箱比“encoding”更流行。 (2认同)