使用 JSCH 通过 SFTP 下载文件 (android)

Downloading file via SFTP using JSCH (android)

我正在尝试制作一个使用 SFTP 从服务器下载文件的应用程序。每当我 运行 调试器时,一切似乎都很好,没有错误。我的日志说它已经下载了指定的文件。但是,我似乎无法在我的设备中的任何位置找到应该下载的文件。有帮助吗?

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import java.util.List;


public class MainActivity extends Activity {

    private String user = "user";
    private String pass = "pass";
    private String host = "hostname";
    private int portNum = 22;

    private String fileName = "sample.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new AsyncTask<Void, Void, List<String>>() {
            @Override
            protected List<String> doInBackground(Void... params) {
                try {
                    Downloader(fileName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }

        }.execute();
    }

    public void Downloader(String fileName) {

        JSch jsch = new JSch();
        Session session = null;

        String knownHostsDir = "/home/user/";

        try {
            jsch.setKnownHosts(knownHostsDir);
        } catch (JSchException e) {
            e.printStackTrace();
        }

        try {

            session = jsch.getSession(user, host, portNum);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(pass);
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;
            sftpChannel.get(fileName);

            Log.d(fileName, " has been downloaded");

            sftpChannel.exit();
            session.disconnect();

        } catch (JSchException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }

}
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.get(fileName);
Log.d(fileName, " has been downloaded");

single-argument version of ChannelSftp.get() 不会将远程文件写入本地文件。它 returns 一个 InputStream。您应该从 InputStream 读取远程文件的内容,例如:

try (FileOutputStream out = new FileOutputStream("/some/file")) {
    try (InputStream in = sftpChannel.get(fileName)) {
        // read from in, write to out
        byte[] buffer = new byte[1024];
        int len;
        while ((len = in.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
    }
}

或者,other versions of the get() method 可以将远程内容写入本地文件。