如何使用 Java 将存储在远程 SFTP 服务器中的文件复制到同一远程服务器中的另一个文件夹?

How do I copy files stored in a remote SFTP server to another folder in the same remote server using Java?

我一直在尝试将远程服务器中的几个选定文件(执行几次检查后)复制到同一远程服务器,使用:

File localFile = new File(srcPath);
sftpChannel.put(localFile.getAbsolutePath(),localFile.getName());

我什至尝试使用 get() 方法将那些选定的文件复制到我的本地计算机。

有人可以帮忙吗?

核心 SFTP 协议不支持复制远程文件。

copy-file/copy-data extensions to the protocol. But those are supported by only few SFTP servers. In the most widespread OpenSSH SFTP server it is supported only by very recent version 9.0. Other servers are for example ProFTPD mod_sftp 和 Bitvise SFTP 服务器的草稿。

JSch 库不支持扩展。

备选方案:

  • 如果您有 shell 访问权限,请打开“执行”通道,然后使用 shell cp 命令(或服务器 OS 的等效命令)。
    参见 Exec.java example
  • 否则,您唯一的选择是将文件下载到本地临时位置并将其副本上传回 different/target 远程目录。或者,避免临时文件。

另见 How can I copy/duplicate a file to another directory using SFTP?