Transferring a File Through SFTP in Java – 在Java中通过SFTP传输文件

最后修改: 2019年 7月 21日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll discuss how to upload and download files from a remote server using SFTP in Java.

在本教程中,我们将讨论如何在Java中使用SFTP从远程服务器上传和下载文件

We’ll use three different libraries: JSch, SSHJ, and Apache Commons VFS.

我们将使用三个不同的库。JSch、SSHJ和Apache Commons VFS。

2. Using JSch

2.使用JSch

First, let’s see how to upload and download files from a remote server using the JSch library.

首先,让我们看看如何使用JSch库从远程服务器上传和下载文件。

2.1. Maven Configuration

2.1.Maven配置

We’ll need to add the jsch dependency to our pom.xml:

我们需要将jsch依赖性添加到我们的pom.xml

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

The latest version of jsch can be found on Maven Central.

jsch的最新版本可以在Maven Central上找到。

2.2. Setting Up JSch

2.2.设置JSch

Now we’ll set up JSch.

现在我们将设置JSch。

JSch enables us to use either Password Authentication or Public Key Authentication to access a remote server. In this example, we’ll use password authentication:

JSch使我们可以使用密码认证或公钥认证来访问远程服务器。在这个例子中,我们将使用密码认证

private ChannelSftp setupJsch() throws JSchException {
    JSch jsch = new JSch();
    jsch.setKnownHosts("/Users/john/.ssh/known_hosts");
    Session jschSession = jsch.getSession(username, remoteHost);
    jschSession.setPassword(password);
    jschSession.connect();
    return (ChannelSftp) jschSession.openChannel("sftp");
}

In the example above, the remoteHost represents the name or IP address of the remote server (i.e. example.com). We can define the variables used in the test as:

在上面的例子中,remoteHost代表远程服务器的名称或IP地址(即example.com)。我们可以将测试中使用的变量定义为。

private String remoteHost = "HOST_NAME_HERE";
private String username = "USERNAME_HERE";
private String password = "PASSWORD_HERE";

We can also generate the known_hosts file using the following command:

我们也可以使用以下命令生成known_hosts文件。

ssh-keyscan -H -t rsa REMOTE_HOSTNAME >> known_hosts

2.3. Uploading a File With JSch

2.3.用JSch上传文件

To upload a file to the remote server, we’ll use the method ChannelSftp.put():

为了向远程服务器上传一个文件,我们将使用ChannelSftp.put()方法。

@Test
public void whenUploadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
    ChannelSftp channelSftp = setupJsch();
    channelSftp.connect();
 
    String localFile = "src/main/resources/sample.txt";
    String remoteDir = "remote_sftp_test/";
 
    channelSftp.put(localFile, remoteDir + "jschFile.txt");
 
    channelSftp.exit();
}

In this example, the first parameter of the method represents the local file to be transferred, src/main/resources/sample.txt, while remoteDir is the path of the target directory at the remote server.

在这个例子中,方法的第一个参数代表要传输的本地文件,src/main/resources/sample.txt,remoteDir是远程服务器上目标目录的路径。

2.4. Downloading a File With JSch

2.4.用JSch下载文件

We can also download a file from the remote server using ChannelSftp.get():

我们还可以使用ChannelSftp.get()从远程服务器下载一个文件。

@Test
public void whenDownloadFileUsingJsch_thenSuccess() throws JSchException, SftpException {
    ChannelSftp channelSftp = setupJsch();
    channelSftp.connect();
 
    String remoteFile = "welcome.txt";
    String localDir = "src/main/resources/";
 
    channelSftp.get(remoteFile, localDir + "jschFile.txt");
 
    channelSftp.exit();
}

The remoteFile is the path of the file to be downloaded, and localDir represents the path of the target local directory.

remoteFile是要下载的文件的路径,localDir代表目标本地目录的路径。

3. Using SSHJ

3.使用SSHJ

Next, we’ll use the SSHJ library to upload and download files from a remote server.

接下来,我们将使用SSHJ库来从远程服务器上传和下载文件。

3.1. Maven Configuration

3.1.Maven配置

First, we’ll add the dependency to our pom.xml:

首先,我们将依赖关系添加到我们的pom.xml

<dependency>
    <groupId>com.hierynomus</groupId>
    <artifactId>sshj</artifactId>
    <version>0.27.0</version>
</dependency>

The latest version of sshj can be found on Maven Central.

最新版本的sshj可以在Maven Central上找到。

3.2. Setting Up SSHJ

3.2.设置SSHJ

Then we’ll set up the SSHClient.

然后我们将设置SSHClient

SSHJ also allows us to use Password or Public Key Authentication to access the remote server.

SSHJ还允许我们使用密码或公钥认证来访问远程服务器。

We’ll use the Password Authentication in our example:

在我们的例子中,我们将使用密码认证的方式。

private SSHClient setupSshj() throws IOException {
    SSHClient client = new SSHClient();
    client.addHostKeyVerifier(new PromiscuousVerifier());
    client.connect(remoteHost);
    client.authPassword(username, password);
    return client;
}

3.3. Uploading a File With SSHJ

3.3.用SSHJ上传文件

Similar to JSch, we’ll use the SFTPClient.put() method to upload a file to the remote server:

与JSch类似,我们将使用SFTPClient.put()方法向远程服务器上传一个文件

@Test
public void whenUploadFileUsingSshj_thenSuccess() throws IOException {
    SSHClient sshClient = setupSshj();
    SFTPClient sftpClient = sshClient.newSFTPClient();
 
    sftpClient.put(localFile, remoteDir + "sshjFile.txt");
 
    sftpClient.close();
    sshClient.disconnect();
}

We have two new variables here to define:

我们在这里有两个新的变量需要定义。

private String localFile = "src/main/resources/input.txt";
private String remoteDir = "remote_sftp_test/";

3.4. Downloading a File With SSHJ

3.4.用SSHJ下载文件

The same goes for downloading a file from the remote server; we’ll use SFTPClient.get():

从远程服务器下载文件也是如此;我们将使用SFTPClient.get()

@Test
public void whenDownloadFileUsingSshj_thenSuccess() throws IOException {
    SSHClient sshClient = setupSshj();
    SFTPClient sftpClient = sshClient.newSFTPClient();
 
    sftpClient.get(remoteFile, localDir + "sshjFile.txt");
 
    sftpClient.close();
    sshClient.disconnect();
}

And we’ll add the two variables used above:

而我们将添加上面使用的两个变量。

private String remoteFile = "welcome.txt";
private String localDir = "src/main/resources/";

4. Using Apache Commons VFS

4.使用Apache Commons VFS

Finally, we’ll use Apache Commons VFS to transfer files to a remote server.

最后,我们将使用Apache Commons VFS将文件传输到远程服务器。

In fact, Apache Commons VFS uses JSch library internally.

事实上,Apache Commons VFS内部使用JSch库

4.1. Maven Configuration

4.1.Maven配置

We need to add the commons-vfs2 dependency to our pom.xml:

我们需要将commons-vfs2依赖性添加到我们的pom.xml

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-vfs2</artifactId>
    <version>2.4</version>
</dependency>

The latest version of commons-vfs2 can be found on Maven Central.

最新版本的commons-vfs2可以在Maven Central上找到。

4.2. Uploading a File With Apache Commons VFS

4.2.用Apache Commons VFS上传文件

Apache Commons VFS is a little different.

Apache Commons VFS有一点不同。

We’ll use a FileSystemManager to create FileObjects from our target files, then use the FileObjects to transfer our files.

我们将使用FileSystemManager从目标文件中创建FileObjects,然后使用FileObjects来传输我们的文件。

In this example, we’ll upload a file by using the method FileObject.copyFrom():

在这个例子中,我们将通过使用FileObject.copyFrom()方法上传一个文件。

@Test
public void whenUploadFileUsingVfs_thenSuccess() throws IOException {
    FileSystemManager manager = VFS.getManager();
 
    FileObject local = manager.resolveFile(
      System.getProperty("user.dir") + "/" + localFile);
    FileObject remote = manager.resolveFile(
      "sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteDir + "vfsFile.txt");
 
    remote.copyFrom(local, Selectors.SELECT_SELF);
 
    local.close();
    remote.close();
}

Note that the local file path should be absolute, and the remote file path should start with sftp://username:password@remoteHost.

注意,本地文件路径应该是绝对的,而远程文件路径应该以sftp://username:password@remoteHost.开头。

4.3. Downloading a File With Apache Commons VFS

4.3.用Apache Commons VFS下载文件

Downloading a file from a remote server is very similar; we’ll also use FileObject.copyFrom() to copy localFile from remoteFile:

从远程服务器下载文件非常类似;我们还将使用FileObject.copyFrom()来从remoteFile复制localFile

@Test
public void whenDownloadFileUsingVfs_thenSuccess() throws IOException {
    FileSystemManager manager = VFS.getManager();
 
    FileObject local = manager.resolveFile(
      System.getProperty("user.dir") + "/" + localDir + "vfsFile.txt");
    FileObject remote = manager.resolveFile(
      "sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteFile);
 
    local.copyFrom(remote, Selectors.SELECT_SELF);
 
    local.close();
    remote.close();
}

5. Conclusion

5.结论

In this article, we learned how to upload and download files from a remote SFTP server in Java. To do this, we used multiple libraries: JSch, SSHJ, and Apache Commons VFS.

在这篇文章中,我们学习了如何用Java从远程SFTP服务器上传和下载文件。为了做到这一点,我们使用了多个库。JSch、SSHJ和Apache Commons VFS。

The full source code can be found over on GitHub.

完整的源代码可以在GitHub上找到over