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

标签 file asynchronous 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);

如何使用 tokio 和异步 fs 方法将 src.txt 复制到 dest.txt 中?

这里是 Playground 的链接

最佳答案

现在 tokio::fsTokio 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::ioCopy 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);

Playground


您的代码无法正常工作,因为 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/

相关文章:

perl - 如何在 Perl 中获取文件元信息?

rust - 有没有办法检查应用程序运行的操作系统是 32 位还是 64 位?

javascript - jQuery 推迟了 : Nesting promises in methods, 最后一次回调太早

linux - 为什么ldconfig能够找到一个库,但是找不到Rust?

pointers - 为什么在 Rust 中修改字符串变量时指针地址没有改变?

c - 在C中替换文件的特定文本

macos - Swift OS X - 将 .jpeg 保存到 NSImage 数组中

c# - os.access 在 IronPython 中为 os.F_OK 模式返回无用值

asynchronous - 带有 zmq_proxy 和回复的 ZeroMQ 异步客户端

javascript - Promise 异步调用