pub struct File { /* private fields */ }展开描述
对文件系统上已打开文件的引用。
This is a specialized version of std::fs::File for usage from the
Tokio 运行时。
根据打开文件时使用的选项,
可以对 File 实例
进行读和/或写操作。
文件还实现 AsyncSeek,
用于更改文件内部
维护的逻辑游标。
如果还有
未完成的 IO 操作,
那么当文件超出其作用域时,
它不会
立即被关闭。
若要确保文件在丢弃时
立即被关闭,
应在丢弃前
调用
flush。
请注意,
这并不能保证文件
已完全写入磁盘;
操作系统可能
将更改保留在内存缓冲区中。
请参阅
sync_all
方法,
以告知操作系统
将数据
写入磁盘。
对 File 的读写
通常使用
AsyncReadExt
和 AsyncWriteExt
trait 中的便利方法来完成。
§示例
创建一个新文件 并向其异步写入字节:
use tokio::fs::File;
use tokio::io::AsyncWriteExt; // for write_all()
let mut file = File::create("foo.txt").await?;
file.write_all(b"hello, world!").await?;将文件的内容读取到缓冲区中:
use tokio::fs::File;
use tokio::io::AsyncReadExt; // for read_to_end()
let mut file = File::open("foo.txt").await?;
let mut contents = vec![];
file.read_to_end(&mut contents).await?;
println!("len = {}", contents.len());实现§
Source§impl File
impl File
Sourcepub async fn open(path: impl AsRef<Path>) -> Result<File>
pub async fn open(path: impl AsRef<Path>) -> Result<File>
尝试以只读模式打开一个文件。
更多详情请参阅 OpenOptions。
§Errors
如果在 Tokio 运行时之外调用此函数,或者路径
尚不存在,则此函数将返回错误。
根据 OpenOptions::open 的定义,也可能会返回其他错误。
§示例
use tokio::fs::File;
use tokio::io::AsyncReadExt;
let mut file = File::open("foo.txt").await?;
let mut contents = vec![];
file.read_to_end(&mut contents).await?;
println!("len = {}", contents.len());read_to_end 方法定义于 AsyncReadExt trait 上。
Sourcepub async fn create(path: impl AsRef<Path>) -> Result<File>
pub async fn create(path: impl AsRef<Path>) -> Result<File>
以只写模式打开一个文件。
如果文件不存在,此函数将创建该文件; 如果文件已存在,则会将其截断。
更多详情请参阅 OpenOptions。
§Errors
如果在 Tokio 运行时之外调用,或底层的
create 调用导致错误,则
会返回错误。
§示例
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
let mut file = File::create("foo.txt").await?;
file.write_all(b"hello, world!").await?;write_all 方法定义于 AsyncWriteExt trait 上。
Sourcepub async fn create_new<P: AsRef<Path>>(path: P) -> Result<File>
pub async fn create_new<P: AsRef<Path>>(path: P) -> Result<File>
以读写模式打开一个文件。
如果文件不存在,此函数将创建该文件;如果文件已存在, 则返回错误。这样,如果调用成功,则可以 保证返回的文件是新建的。
此选项很有用,因为它是原子操作。否则,在检查 文件是否存在和创建新文件之间,文件 可能被另一个进程创建(TOCTOU 竞争条件 / 攻击)。
这也可以通过 File::options().read(true).write(true).create_new(true).open(...) 来编写。
更多详情请参阅 OpenOptions。
§示例
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
let mut file = File::create_new("foo.txt").await?;
file.write_all(b"hello, world!").await?;write_all 方法定义于 AsyncWriteExt trait 上。
Sourcepub fn options() -> OpenOptions
pub fn options() -> OpenOptions
返回一个新的 OpenOptions 对象。
此函数返回一个新的 OpenOptions 对象,如果 open()
或 create() 不合适,你可以使用它以
特定选项打开或创建文件。
它等价于 OpenOptions::new(),但使你能够编写更
易读的代码。与其写
OpenOptions::new().append(true).open("example.log"),
你可以写 File::options().append(true).open("example.log")。
这样还可以避免导入 OpenOptions。
更多详情请参阅 OpenOptions::new 函数。
§示例
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
let mut f = File::options().append(true).open("example.log").await?;
f.write_all(b"new line\n").await?;Sourcepub fn from_std(std: StdFile) -> File
pub fn from_std(std: StdFile) -> File
将 std::fs::File 转换为 tokio::fs::File。
§示例
// This line could block. It is not recommended to do this on the Tokio
// runtime.
let std_file = std::fs::File::open("foo.txt").unwrap();
let file = tokio::fs::File::from_std(std_file);Sourcepub async fn sync_all(&self) -> Result<()>
pub async fn sync_all(&self) -> Result<()>
尝试将所有操作系统内部元数据同步到磁盘。
此函数将尝试确保所有核心内数据在返回之前 到达文件系统。
§示例
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
let mut file = File::create("foo.txt").await?;
file.write_all(b"hello, world!").await?;
file.sync_all().await?;write_all 方法定义于 AsyncWriteExt trait 上。
Sourcepub async fn sync_data(&self) -> Result<()>
pub async fn sync_data(&self) -> Result<()>
此函数与 sync_all 类似,只是它可能
不会将文件元数据同步到文件系统。
此方法适用于必须同步内容,但不需要 磁盘上的元数据的场景。该方法的目标是减少 磁盘操作。
请注意,某些平台可能只是通过 sync_all 来实现此功能。
§示例
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
let mut file = File::create("foo.txt").await?;
file.write_all(b"hello, world!").await?;
file.sync_data().await?;write_all 方法定义于 AsyncWriteExt trait 上。
Sourcepub async fn set_len(&self, size: u64) -> Result<()>
pub async fn set_len(&self, size: u64) -> Result<()>
截断或扩展底层文件,将此文件的大小更新为指定的大小。
如果该大小小于文件的当前大小,则 文件将被缩减。如果大于文件的当前大小, 则文件将扩展到该大小,并且 中间的所有数据都将填充为 0。
§Errors
如果文件没有以写入方式打开, 此函数将返回错误。
§示例
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
let mut file = File::create("foo.txt").await?;
file.write_all(b"hello, world!").await?;
file.set_len(10).await?;write_all 方法定义于 AsyncWriteExt trait 上。
Sourcepub async fn metadata(&self) -> Result<Metadata>
pub async fn metadata(&self) -> Result<Metadata>
查询底层文件的元数据。
§示例
use tokio::fs::File;
let file = File::open("foo.txt").await?;
let metadata = file.metadata().await?;
println!("{:?}", metadata);Sourcepub async fn try_clone(&self) -> Result<File>
pub async fn try_clone(&self) -> Result<File>
创建一个新的 File 实例,与现有的 File 实例
共享相同的底层文件句柄。读、写和寻
作会同时影响两个 File 实例。
§示例
use tokio::fs::File;
let file = File::open("foo.txt").await?;
let file_clone = file.try_clone().await?;Sourcepub async fn into_std(self) -> StdFile
pub async fn into_std(self) -> StdFile
将 File 解构为 std::fs::File。此函数是
异步的,以便让任何进行中的
操作完成。
使用 File::try_into_std 尝试立即转换。
§示例
use tokio::fs::File;
let tokio_file = File::open("foo.txt").await?;
let std_file = tokio_file.into_std().await;Sourcepub fn try_into_std(self) -> Result<StdFile, Self>
pub fn try_into_std(self) -> Result<StdFile, Self>
尝试立即将 File 解构为 std::fs::File。
§Errors
如果有正在进行的操作, 此函数将返回一个包含该文件的错误。
§示例
use tokio::fs::File;
let tokio_file = File::open("foo.txt").await?;
let std_file = tokio_file.try_into_std().unwrap();Sourcepub async fn set_permissions(&self, perm: Permissions) -> Result<()>
pub async fn set_permissions(&self, perm: Permissions) -> Result<()>
更改底层文件的权限。
§Platform-specific behavior
此函数当前对应于 Unix 上的 fchmod 函数以及
Windows 上的 SetFileInformationByHandle 函数。请注意,
此行为将来可能会改变。
§Errors
如果用户缺少对底层文件的权限更改 权限,此函数将返回错误。在其他 未明确说明的特定于操作系统的场景下,它也可能返回错误。
§示例
use tokio::fs::File;
let file = File::open("foo.txt").await?;
let mut perms = file.metadata().await?.permissions();
perms.set_readonly(true);
file.set_permissions(perms).await?;Sourcepub fn set_max_buf_size(&mut self, max_buf_size: usize)
pub fn set_max_buf_size(&mut self, max_buf_size: usize)
设置底层 AsyncRead / AsyncWrite 操作的最大缓冲区大小。
尽管 Tokio 为此缓冲区大小使用了合理的默认值,但根据不同 情况,此函数可用于更改该默认值。
§示例
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
let mut file = File::open("foo.txt").await?;
// Set maximum buffer size to 8 MiB
file.set_max_buf_size(8 * 1024 * 1024);
let mut buf = vec![1; 1024 * 1024 * 1024];
// Write the 1 GiB buffer in chunks up to 8 MiB each.
file.write_all(&mut buf).await?;Sourcepub fn max_buf_size(&self) -> usize
pub fn max_buf_size(&self) -> usize
获取底层 AsyncRead / AsyncWrite 操作的最大缓冲区大小。
Trait 实现§
Source§impl AsHandle for File
Available on docsrs, or Windows only.
impl AsHandle for File
docsrs, or Windows only.Source§fn as_handle(&self) -> BorrowedHandle<'_>
fn as_handle(&self) -> BorrowedHandle<'_>
Source§impl AsRawHandle for File
Available on docsrs, or Windows only.
impl AsRawHandle for File
docsrs, or Windows only.Source§fn as_raw_handle(&self) -> RawHandle
fn as_raw_handle(&self) -> RawHandle
Source§impl AsyncWrite for File
impl AsyncWrite for File
Source§fn poll_write(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
src: &[u8],
) -> Poll<Result<usize>>
fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, src: &[u8], ) -> Poll<Result<usize>>
buf into the object. 更多信息Source§fn poll_write_vectored(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
bufs: &[IoSlice<'_>],
) -> Poll<Result<usize, Error>>
fn poll_write_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>], ) -> Poll<Result<usize, Error>>
poll_write, except that it writes from a slice of buffers. 更多信息Source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
poll_write_vectored
implementation. 更多信息Source§impl FromRawHandle for File
Available on docsrs, or Windows only.
impl FromRawHandle for File
docsrs, or Windows only.Source§unsafe fn from_raw_handle(handle: RawHandle) -> Self
unsafe fn from_raw_handle(handle: RawHandle) -> Self
自动 Trait 实现§
impl !Freeze for File
impl !RefUnwindSafe for File
impl Send for File
impl Sync for File
impl Unpin for File
impl UnsafeUnpin for File
impl !UnwindSafe for File
Blanket 实现§
Source§impl<R> AsyncReadExt for R
impl<R> AsyncReadExt for R
Source§fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self>where
Self: Unpin,
fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> Read<'a, Self>where
Self: Unpin,
Source§fn read_buf<'a, B>(&'a mut self, buf: &'a mut B) -> ReadBuf<'a, Self, B>
fn read_buf<'a, B>(&'a mut self, buf: &'a mut B) -> ReadBuf<'a, Self, B>
Source§fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExact<'a, Self>where
Self: Unpin,
fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExact<'a, Self>where
Self: Unpin,
buf. 更多信息Source§fn read_u8(&mut self) -> ReadU8<&mut Self>where
Self: Unpin,
fn read_u8(&mut self) -> ReadU8<&mut Self>where
Self: Unpin,
Source§fn read_i8(&mut self) -> ReadI8<&mut Self>where
Self: Unpin,
fn read_i8(&mut self) -> ReadI8<&mut Self>where
Self: Unpin,
Source§fn read_u16(&mut self) -> ReadU16<&mut Self>where
Self: Unpin,
fn read_u16(&mut self) -> ReadU16<&mut Self>where
Self: Unpin,
Source§fn read_i16(&mut self) -> ReadI16<&mut Self>where
Self: Unpin,
fn read_i16(&mut self) -> ReadI16<&mut Self>where
Self: Unpin,
Source§fn read_u32(&mut self) -> ReadU32<&mut Self>where
Self: Unpin,
fn read_u32(&mut self) -> ReadU32<&mut Self>where
Self: Unpin,
Source§fn read_i32(&mut self) -> ReadI32<&mut Self>where
Self: Unpin,
fn read_i32(&mut self) -> ReadI32<&mut Self>where
Self: Unpin,
Source§fn read_u64(&mut self) -> ReadU64<&mut Self>where
Self: Unpin,
fn read_u64(&mut self) -> ReadU64<&mut Self>where
Self: Unpin,
Source§fn read_i64(&mut self) -> ReadI64<&mut Self>where
Self: Unpin,
fn read_i64(&mut self) -> ReadI64<&mut Self>where
Self: Unpin,
Source§fn read_u128(&mut self) -> ReadU128<&mut Self>where
Self: Unpin,
fn read_u128(&mut self) -> ReadU128<&mut Self>where
Self: Unpin,
Source§fn read_i128(&mut self) -> ReadI128<&mut Self>where
Self: Unpin,
fn read_i128(&mut self) -> ReadI128<&mut Self>where
Self: Unpin,
Source§fn read_f32(&mut self) -> ReadF32<&mut Self>where
Self: Unpin,
fn read_f32(&mut self) -> ReadF32<&mut Self>where
Self: Unpin,
Source§fn read_f64(&mut self) -> ReadF64<&mut Self>where
Self: Unpin,
fn read_f64(&mut self) -> ReadF64<&mut Self>where
Self: Unpin,
Source§fn read_u16_le(&mut self) -> ReadU16Le<&mut Self>where
Self: Unpin,
fn read_u16_le(&mut self) -> ReadU16Le<&mut Self>where
Self: Unpin,
Source§fn read_i16_le(&mut self) -> ReadI16Le<&mut Self>where
Self: Unpin,
fn read_i16_le(&mut self) -> ReadI16Le<&mut Self>where
Self: Unpin,
Source§fn read_u32_le(&mut self) -> ReadU32Le<&mut Self>where
Self: Unpin,
fn read_u32_le(&mut self) -> ReadU32Le<&mut Self>where
Self: Unpin,
Source§fn read_i32_le(&mut self) -> ReadI32Le<&mut Self>where
Self: Unpin,
fn read_i32_le(&mut self) -> ReadI32Le<&mut Self>where
Self: Unpin,
Source§fn read_u64_le(&mut self) -> ReadU64Le<&mut Self>where
Self: Unpin,
fn read_u64_le(&mut self) -> ReadU64Le<&mut Self>where
Self: Unpin,
Source§fn read_i64_le(&mut self) -> ReadI64Le<&mut Self>where
Self: Unpin,
fn read_i64_le(&mut self) -> ReadI64Le<&mut Self>where
Self: Unpin,
Source§fn read_u128_le(&mut self) -> ReadU128Le<&mut Self>where
Self: Unpin,
fn read_u128_le(&mut self) -> ReadU128Le<&mut Self>where
Self: Unpin,
Source§fn read_i128_le(&mut self) -> ReadI128Le<&mut Self>where
Self: Unpin,
fn read_i128_le(&mut self) -> ReadI128Le<&mut Self>where
Self: Unpin,
Source§fn read_f32_le(&mut self) -> ReadF32Le<&mut Self>where
Self: Unpin,
fn read_f32_le(&mut self) -> ReadF32Le<&mut Self>where
Self: Unpin,
Source§fn read_f64_le(&mut self) -> ReadF64Le<&mut Self>where
Self: Unpin,
fn read_f64_le(&mut self) -> ReadF64Le<&mut Self>where
Self: Unpin,
Source§fn read_to_end<'a>(&'a mut self, buf: &'a mut Vec<u8>) -> ReadToEnd<'a, Self>where
Self: Unpin,
fn read_to_end<'a>(&'a mut self, buf: &'a mut Vec<u8>) -> ReadToEnd<'a, Self>where
Self: Unpin,
buf. 更多信息