3

“如何使用 Jsch 复制文件?” 是第一个问题。由于使用 Jsch 复杂且容易出错,而且工作级别非常低,因此您需要编写几行代码才能使简单的 scp 工作。

那么,如何在Java中用尽可能少的代码行来实现一个 scp(甚至 sftp)并且不违反 DRY 原则?

4

2 回答 2

5

您可以使用 Ant scp 任务使用的库:

package org.example.scp;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.optional.ssh.Scp;

public class ScpCopyExample {

    public void downloadFile( String remoteFilePath, String localFilePath ) {
        Scp scp = new Scp();
        scp.setFile("username:password@host.example.org:" + remoteFilePath);
        scp.setLocalTofile(localFilePath);
        scp.setProject(new Project()); // prevent a NPE (Ant works with projects)
        scp.setTrust(true); // workaround for not supplying known hosts file

        scp.execute();
    }

    public static void main(String[] args) {
        ScpCopyExample scpDemo = new ScpCopyExample();
        scpDemo.downloadFile("~/test.txt", "testlocal.txt");
    }

}

我在我的类路径中使用以下 jar 来做到这一点:

  • jsch-0.1.48.jar
  • ant-jsch-1.6.5.jar
  • 蚂蚁1.7.0.jar
  • ant-launcher-1.7.0.jar

此示例可以轻松扩展为上传文件或使用 SFTP。

于 2012-09-12T11:43:41.917 回答
1

尽可能少的线路?试试这个利用ANT scp 任务的 groovy 示例。

@Grapes([
    @Grab(group='org.apache.ant', module='ant-jsch', version='1.8.4'),
    @GrabConfig(systemClassLoader=true)
])

def ant = new AntBuilder()    
ant.scp(file:"helloworld.doc", todir:"mark@remotehost:/home/mark/docs", password:"sEcReT")

The Grape annotations will download the jar dependencies at run-time.

于 2012-09-12T20:46:36.153 回答