Skip to content
Advertisement

Using SFTP in Java, How do I transfer a file from one folder to another? [closed]

I have a simple directory with two folders –

enter image description here

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!

Advertisement

Answer

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. In the most widespread OpenSSH SFTP server it is supported only by very recent version 9.0. 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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement