tags:

views:

519

answers:

3

Hi

I'm looking for a dead simple Java Library to use for SFTP file transfers. I don't need any other features beyond that.

I've tried Zehon's, but it's incredible naggy, and I think 8 jar files is a bit crazy for so little functionality as I require.

And the library have to be free (as in free beer), and preferable Open Source (not a requirement).

Thanks.

A: 

How about FTPSClient from Apache Commons?

Konrad Garus
What you're suggesting is FTPS, not SFTP.
Valentin Rocher
+5  A: 

Using JSch (a java ssh lib, used by Ant for example), you could do something like that :

Session session = null;
Channel channel = null;
try {
 JSch ssh = new JSch();
 ssh.setKnownHosts("/path/of/known_hosts/file");
 session = ssh.getSession("username", "host", 22);
 session.setPassword("password");
 session.connect();
 channel = session.openChannel("sftp");
 channel.connect();
 ChannelSftp sftp = (ChannelSftp) channel;
 sftp.put("/path/of/local/file", "/path/of/ftp/file");
 } catch (JSchException e) {
  e.printStackTrace();
 } catch (SftpException e) {
  e.printStackTrace();
 }
 finally {
  if (channel != null)
  {
   channel.disconnect();
  }
  if (session != null)
  {
   session.disconnect();
  }
 }
}

Here is another link using JSch to do SFTP.

You can use JSch directly this way, or through Commons VFS, but then you'll have to have both commons vfs jar and jsch jar.

Valentin Rocher
That's read only , no?
Claus Jørgensen
I found a simpler way to do it, I'll edit my answer.
Valentin Rocher
JSch is a great library but is severely lacking in documentation. I found http://timarcher.com/node/57 was a really helpful example.
UmYeah
Thanks for the link, I'll add it to the answer. Indeed, JSch really lacks documentation (and source code readability, it's like they released it in the wild), but it does the job perfectly.
Valentin Rocher
+1  A: 

Here is the complete source code of an example using JSch without having to worry about the ssh key checking.

import com.jcraft.jsch.*;

public class TestJSch {
    public static void main(String args[]) {
        JSch jsch = new JSch();
        Session session = null;
        try {
            session = jsch.getSession("username", "127.0.0.1", 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword("password");
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp) channel;
            sftpChannel.get("remotefile.txt", "localfile.txt");
            sftpChannel.exit();
            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }
}
Iraklis