如何在不将数据读入内存的情况下将 ssh2::Stream 写入文件?

How can I write a ssh2::Stream to a file without reading the data into memory?

我正在尝试使用 ssh2 crate v0.3.3.

通过 SCP 下载一个大型二进制文件
extern crate ssh2;

use std::net::TcpStream;
use ssh2::Session;
use std::path::Path;
use std::fs::File;
use indicatif::ProgressBar;

fn main() -> Result<(), Box<std::error::Error>> {
    let ssh_host_port = "prokerala.com:22";
    let ssh_user = "prokeral";
    let remote_temp_file = "/tmp/dbimport_Rk6Iwwm5.sql.bz2";

    let tcp = TcpStream::connect(&ssh_host_port).unwrap();
    let mut sess = Session::new().unwrap();
    sess.handshake(&tcp).expect("SSH handshake failed");
    let _ = sess.userauth_agent(ssh_user);

    let path = Path::new(&remote_temp_file);
    let (mut remote_file, stat) = sess.scp_recv(path).unwrap();

    let stream:ssh2::Stream = remote_file.stream(1);

    // Update: solved by using io::copy as suggested by @apemanzilla below
    // let mut target = File::create("/tmp/done.txt").unwrap();
    // let pb = ProgressBar::new(stat.size());
    // std::io::copy(&mut pb.wrap_read(remote_file), &mut target)?;
    Ok(())
}

我想将 stream 写入文件,并显示进度条。是否可以直接将 stream 写入文件,而无需在循环中使用 stream.read() 将数据读入内存?

由于 Stream 实现了 Read,您应该可以只使用 std::io::copy(&mut stream, &mut File::create(...).unwrap()) 将所有数据复制到一个文件中。如果你想要进度条,我建议使用 indicatif crate, which has a method to wrap a Read instance,在读取数据时自动更新进度条。