如何使用 tokio::fs 复制文件

Nic*_*ick 3 asynchronous file rust rust-tokio

我正在尝试使用 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);
Run Code Online (Sandbox Code Playgroud)

如何复制src.txtdest.txt使用 tokio 和 asyncfs方法?

这是游乐场的链接

Öme*_*den 5

现在在Tokio 0.2.11版本中tokio::fs有自己的copy实现。(参考

//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(())
}
Run Code Online (Sandbox Code Playgroud)

实现基本上是下面代码的async-await版本,请看源码

没有异步等待(Tokio 0.1.x)

您可以使用Copyfuture from tokio::io,它将所有字节从输入流复制到输出流。

//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);
Run Code Online (Sandbox Code Playgroud)

操场


您的代码不起作用,因为read_buf返回的Poll不是 theFuture所以它不会与内部的结合。如果您生成由(完整代码)创建的小文件,它将为小文件执行相同的工作。Futuretokio::fs::File::create

但请注意read_buf 的参考

从此源中提取一些字节到指定的 BufMut

它不会通过一次调用读取到文件末尾。我不知道为什么这个 read 例子没有警告,它只是说Read the contents of a file into a buffer,它看起来像一个误导性的例子。