文章目录
创建文件,写入内容
File::create
定制化开发创建一个文件,定制化开发定制化开发如果文件已存在,定制化开发则会将文件内容清空。
use std::fs::File;use std::io::prelude::*;// 如果文件已存在,定制化开发则文件内容会被清空let path = "D:/test/hello_rust.txt";//创建文件,mut让文件可以写入let mut f = File::create(path)?;// 写入字节数组let bytes: &[u8] = b"Some Text;\r\";f.write_all(bytes)?;// rust中文件不用手动关闭// 编译器会将超出作用域的文件自动进行关闭// 写入中文内容let txt = "hello你好;";// rust中字符串默认按utf-8方式编码f.write_all(txt.as_bytes());
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
Rust中打开的文件不用手动关闭,编译器会跟踪超出作用域的文件句柄,自动进行关闭。
往文件中追加内容(append)
将OpenOptions
的append
属性为true
,再open
文件,则会在文件末尾进行内容追加。
use std::fs::OpenOptions;let mut file = OpenOptions::new() .read(true) .write(true) .create(true) .append(true) .open(path).unwrap();file.write_all(txt.as_bytes());
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
打开已存在文件
File::open
打开已存在的文件,若文件不存在会报错:“系统找不到指定的文件。”。
file.read_to_end(buf: &mut Vec<u8>)
会将整个文件内容读入到buf
中。
file.read_to_string(buf: &mut String)
会将整个文件内容读入到buf
中。
//打开已存在的文件,若文件不存在会报错:"系统找不到指定的文件。"let mut x: File = File::open(path)?;let mut buf: Vec<u8> = Vec::new();x.read_to_end(&mut buf);let y = String::from_utf8(buf).unwrap();//Some Text;hello你好;println!("{}", y);println!("{}","-".repeat(10));let mut x: File = File::open(path)?;let mut s = String::new();x.read_to_string(&mut s);//Some Text;hello你好;println!("{}", s);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
BufReader按行读取
通过BufReader
包装一个已经打开的文件,可以实现带缓冲的读取。
println!("{}","-".repeat(10));use std::io::BufReader;let mut f: File = File::open(path)?;let br = BufReader::new(f);//按行读取for line in br.lines() { let str: String = line.unwrap(); println!("{}", str);}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
文件写入
写入二进制内容。
// 将整数类型转换成大端字节序(big endian)fn i32_to_u8_array(x: i32) -> [u8; 4] { let mut a = [0u8; 4]; a[0] = ((x>>24)&0xff) as u8; a[1] = ((x>>16)&0xff) as u8; a[2] = ((x>>8)&0xff) as u8; a[3] = (x&0xff) as u8; a}//从大端字节序中还原整数fn read_i32(buf: &[u8]) -> i32 { let mut a: i32 = 0; a += buf[0] as i32; a <<= 8; a += buf[1] as i32; a <<= 8; a += buf[2] as i32; a <<= 8; a += buf[3] as i32; a}//写入二进制内容let mut f = File::create("D:/test/hello_rust_data")?;let v:i32 = 0x7fffffff;let buf = i32_to_u8_array(v);//文件中是二进制内容: 7fff fffff.write(&buf);let result = read_i32(&buf);//2147483647println!("{}", result);
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
BufWriter带缓冲写入
通过BufWriter
包装一个已经打开的文件,可以实现带缓冲的写入。最后记得flush()
,以确保缓冲中的内容全部写入文件。
//创建文件,mut让文件可以写入use std::io::BufWriter;let mut f = File::create(path)?;let mut bw = BufWriter::new(f);// 带缓冲写入bw.write(b"ABC");bw.write(b"123");//确保缓冲中的内容全部写入文件bw.flush();
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9