Rust 的文件操作
一、读操作
1、使用 read_to_string
方法
// 直接读取文件后存入到字符串,文件不存在则报错
let content: String = read_to_string("file_path").unwrap();
2、使用 File::read
方法
use std::fs::File;
use std::io::Read;
// open()是以只读方式打开文件。不能进行写入
let mut file: File = File::open("foo.txt").unwrap();
let mut buf: [u8;32] = [0u8; 32];
// 将文件内容以字节的形式读入到数组中,返回读取的字节数
while let Ok(len) = File::read(&mut file, &mut buf) {
// 读取到文件尾时返回0,结束循环
if len <= 0 {
break;
}
// Note:文件内容由多字节组成,可能会没有完整读入数组
print!("{}", String::from_utf8_lossy(&buf[0..len]));
}
3、使用 BufReader
结构
use std::fs::File;
use std::io::{BufRead, BufReader};
let mut file: File = File::open("foo.txt").unwrap();
let mut reader: BufReader<File> = BufReader::new(file);
// 向缓冲区写入数据
let buf: &[u8] = reader.fill_buf().unwrap();
println!("{}", String::from_utf8_lossy(&buf));
// 按行读取
for line in reader.lines() {
println!("{}", line.unwrap());
}
二、写操作
1、使用 File::write
方法
use std::fs::File;
use std::io::Write;
let content: &str = "Hello, world";
// 以只写的方式打开文件,文件存在则会覆盖原始内容
let mut file: File = File::create("foo.txt").unwrap();
// 以字节的形式写入,返回写入的字节数
let len: usize = file.write(content.as_bytes()).unwrap();
2、使用 BufWriter
结构
use std::fs::File;
use std::fs::OpenOptions;
use std::io::{BufWriter, Write};
let content = "Hello, world";
let file = File::create("foo.txt").unwrap();
// 使用缓冲写入数据到文件
let mut writer = BufWriter::new(file);
let len = writer.write(content.as_bytes()).unwrap();
// 可以提前刷新写入文件
writer.flush().unwrap();
三、读写操作
使用 OpenOptions
结构,进行链式调用创建文件的打开模式
use std::fs::{File, OpenOptions};
use std::io::Write;
let mut file: File = OpenOptions::new()
.read(true)
.append(true) // 以附加的方式在文件尾写入
.open("foo.txt")
.unwrap();
let mut content: String = String::new();
// 将文件内容读取到字符串中,返回读入的长度
let len: usize = file.read_to_string(&mut content).unwrap();
// 将字符串转变为大写形式后写入
file.write(content.to_uppercase().as_bytes()).unwrap();