我正在尝试使用 tokio 复制文件以进行异步操作。我看到 tokio 没有公开任何像 tokio::fs::copy
这样可以为我完成工作的方法(就像等效的 std::fs::copy
用于同步操作)。
在尝试实现这种方法时,我实际上无法使用 tokio::fs::File::create
创建文件,即以下代码不会创建任何文件:
tokio::fs::File::open("src.txt")
.and_then(|mut file| {
let mut content = Vec::new();
file.read_buf(&mut content)
.map(move |_| tokio::fs::File::create("dest.txt"))
})
.map_err(Error::from)
.map(drop);
如何使用 tokio 和异步 fs
方法将 src.txt
复制到 dest.txt
中?
这里是 Playground 的链接
最佳答案
现在 tokio::fs
在 Tokio 0.2.11 版本中有它自己的 copy
实现。 ( reference )
//tokio = {version = "0.2.11", features = ["full"] }
#[tokio::main]
async fn main()-> Result<(), ::std::io::Error>{
tokio::fs::copy("source.txt","target.txt").await?;
Ok(())
}
下面的实现基本上是async-await版本的代码,请看source code
没有异步等待(Tokio 0.1.x)
您可以使用 tokio::io
的 Copy
future,它将所有字节从输入流复制到输出流。
//tokio-0.1.22
tokio::fs::File::open("src.txt")
.and_then(|mut file_in| {
tokio::fs::File::create("dest.txt")
.and_then(move |file_out| tokio::io::copy(file_in, file_out))
})
.map_err(Error::from)
.map(drop);
您的代码无法正常工作,因为 read_buf
返回 Poll
而不是 Future
,因此它不会与内部代码结合。如果您生成由 tokio::fs::File::create
创建的 Future
,它将对小型文件 执行相同的工作( full code )。
但要小心 from the reference of read_buf :
Pull some bytes from this source into the specified BufMut
只有一次调用才会读取到文件末尾。我不知道为什么 this read example 没有警告,它只是说 Read the contents of a file into a buffer,这看起来像是一个误导性的例子。
关于file - 如何使用 tokio::fs 复制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57028769/