0

我想使用 Java 的 Runtime 类从 sftp 服务器下载文件。我不能使用 Jsch 或 SSHJ 之类的库,因为我需要使用 -B 选项来增加缓冲区大小。到目前为止,我已经尝试过使用此代码:

public void download(String source, String destination,String port, String user, String host ){
    Runtime runtime = Runtime.getRuntime();
    String cmd = "sftp -oPort=" + port + " -B 150000 "+ user + "@" + host + ":" + source + " " + destination;

    String[] args = { "/bin/sh", "-c", cmd };
    try {
        long startTime = System.currentTimeMillis();
        log.info("cmd: "+ cmd);
        final Process process = runtime.exec(args);
        process.waitFor();
        long stopTime = System.currentTimeMillis();
        long elapsedTime = stopTime - startTime;
        System.out.println("Time: "+elapsedTime);

        BufferedReader bre = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        StringBuffer sbe = new StringBuffer();
        String lineError;
        while ((lineError = bre.readLine()) != null) {   
          sbe.append(lineError).append("\n");
        }   
        String answerError = sbe.toString();
        if(answerError.length()>0)log.error("Error:"+answerError);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

我收到错误消息:Connecting to xxxxxx... with the name of the host 而不是“xxxxxx”

我已经在 putty 中直接尝试过该命令,效果很好,但是当我在 java 中使用它时,它根本不起作用。我还尝试了一个带有 runtime.exec() 的 scp 命令来下载而不是 sftp,这样就可以了。

有人知道为什么它不起作用吗?我找不到这种方法的例子。或者有人知道允许设置 -B 选项的 sftp 传输库吗?我可能错过了 Jsch 和 Sshj 中的方法。

提前致谢

4

1 回答 1

0

我在 Windows 上使用 psftp 执行此操作。我希望您在 *nix 上使用 sftp 的结果应该是相同的。

 static java.io.File downloadFileViaSftp(String file) {
    String string = null;

    try {
        String c = "psftp -l user -P 22 -v -pw password hostname";
        Process p = Runtime.getRuntime().exec(c);

        OutputStream out = p.getOutputStream();

        Writer out2 = new BufferedWriter(new OutputStreamWriter(out));

        out2.write("get " + file + "\n");
        out2.flush();
        out2.write("close\n");
        out2.flush();
        out2.write("quit\n");
        out2.flush();
        out2.close();

        InputStream in = p.getInputStream();
        InputStream err = p.getErrorStream();

        BufferedReader bufferedreader1 = new BufferedReader(new InputStreamReader(in), 999999);
        BufferedReader bufferedreader2 = new BufferedReader(new InputStreamReader(err), 999999);

        while ((string = bufferedreader2.readLine()) != null) {
            System.out.println("2=" + string);
            System.out.flush();
        }
        bufferedreader2.close();

        while ((string = bufferedreader1.readLine()) != null) {
            System.out.println("1=" + string);
            System.out.flush();
        }
        bufferedreader1.close();

        int x = p.waitFor();
        p.destroy();

    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return new java.io.File(file);

}
于 2014-08-11T19:13:21.163 回答