pub async fn read(path: impl AsRef<Path>) -> Result<Vec<u8>>展开描述
将一个文件的全部内容读取到一个字节向量中。
这是 std::fs::read.
这是一个便捷函数,使用 File::open and read_to_end
with fewer imports and without an intermediate variable. It pre-allocates a
buffer based on the file size when available, so it is generally faster than
reading into a vector created with Vec::new().
此操作通过在单独的线程池上使用 spawn_blocking.
§Errors
如果 path 不存在,此函数将返回错误。
根据 OpenOptions::open,其他错误也可能被返回。
如果在读取过程中遇到 ErrorKind::Interrupted.
§io_uring support
在 Linux 上,你也可以使用 io_uring 来执行系统调用。要启用
io_uring,需要在编译时指定 --cfg tokio_unstable 标志,
启用 io-uring cargo feature,并设置 Builder::enable_io_uring
运行时选项。
对 io_uring 的支持目前仍处于实验阶段,因此其行为可能会在未来的版本中发生变化或被移除。
§示例
use tokio::fs;
use std::net::SocketAddr;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + 'static>> {
let contents = fs::read("address.txt").await?;
let foo: SocketAddr = String::from_utf8_lossy(&contents).parse()?;
Ok(())
}