I have a simple directory with two folders -
In the SFTP_1
folder, I have a bitmap image. And the SFTP_2
folder is just an empty folder.
Does Java have a native SFTP library to use? When I searched I only found a library online called JSch.
How would I get started to run this example? Any tips appreciated, thanks!
There's no native SFTP support in Java.
The JSch library, you have found, is probably the most widely used SFTP implementation for Java.
If you want to move the file from the SFTP_1
to the SFTP_2
using JSch, use the ChannelSftp.rename
method:
channelSftp.rename("/SFTP_1/file.txt", "/SFTP_2/file.txt");
If you want to copy the file, it's more complicated. While there's the copy-file
extension to the SFTP protocol, it's supported by only a few SFTP servers. And it's not supported by the JSch library either.
So in the end, your only option is probably to download the file to a local temporary folder and upload it back to the new location (or use streams, to avoid a temporary file). Or use shell session to invoke a command like cp
. See also
SFTP supports RenameFile and CopyRemoteFile operations but only starting from SFTP protocol version 5 or 6 if memory serves. Our product, SecureBlackbox (Java edition), supports these operations, however it is necessary to ensure that your server supports the required SFTP version and thus the file operations you need.
来源:https://stackoverflow.com/questions/32742066/using-sftp-in-java-how-do-i-transfer-a-file-from-one-folder-to-another