<p>I'm trying to retrieve a file from a server using SFTP (as opposed to FTPS) using Java. How can I do this?</p>

[{'answer_id': 14629, 'author': 'David Hayes', 'author_id': 1769, 'author_profile': 'https://Stackoverflow.com/users/1769', 'pm_score': 5, 'selected': False, 'text': '<p>This was the solution I came up with\n<a href="http://sourceforge.net/projects/sshtools/" rel="noreferrer">http://sourceforge.net/projects/sshtools/</a> (most error handling omitted for clarity). This is an excerpt from <a href="http://www.spindriftpages.net/blog/dave/2007/11/27/sshtools-j2ssh-java-sshsftp-library" rel="noreferrer">my blog</a></p>\n\n<pre><code>SshClient ssh = new SshClient();\nssh.connect(host, port);\n//Authenticate\nPasswordAuthenticationClient passwordAuthenticationClient = new PasswordAuthenticationClient();\npasswordAuthenticationClient.setUsername(userName);\npasswordAuthenticationClient.setPassword(password);\nint result = ssh.authenticate(passwordAuthenticationClient);\nif(result != AuthenticationProtocolState.COMPLETE){\n     throw new SFTPException("Login to " + host + ":" + port + " " + userName + "/" + password + " failed");\n}\n//Open the SFTP channel\nSftpClient client = ssh.openSftpClient();\n//Send the file\nclient.put(filePath);\n//disconnect\nclient.quit();\nssh.disconnect();\n</code></pre>\n'}, {'answer_id': 15937, 'author': 'Cheekysoft', 'author_id': 1820, 'author_profile': 'https://Stackoverflow.com/users/1820', 'pm_score': 9, 'selected': True, 'text': '<p>Another option is to consider looking at the <a href="http://www.jcraft.com/jsch/" rel="noreferrer" title="JSch library">JSch library</a>. JSch seems to be the preferred library for a few large open source projects, including Eclipse, Ant and Apache Commons HttpClient, amongst others.</p>\n\n<p>It supports both user/pass and certificate-based logins nicely, as well as all a whole host  of other yummy SSH2 features.</p>\n\n<p>Here\'s a simple remote file retrieve over SFTP. Error handling is left as an exercise for the reader :-)</p>\n\n<pre><code>JSch jsch = new JSch();\n\nString knownHostsFilename = "/home/username/.ssh/known_hosts";\njsch.setKnownHosts( knownHostsFilename );\n\nSession session = jsch.getSession( "remote-username", "remote-host" );    \n{\n  // "interactive" version\n  // can selectively update specified known_hosts file \n  // need to implement UserInfo interface\n  // MyUserInfo is a swing implementation provided in \n  //  examples/Sftp.java in the JSch dist\n  UserInfo ui = new MyUserInfo();\n  session.setUserInfo(ui);\n\n  // OR non-interactive version. Relies in host key being in known-hosts file\n  session.setPassword( "remote-password" );\n}\n\nsession.connect();\n\nChannel channel = session.openChannel( "sftp" );\nchannel.connect();\n\nChannelSftp sftpChannel = (ChannelSftp) channel;\n\nsftpChannel.get("remote-file", "local-file" );\n// OR\nInputStream in = sftpChannel.get( "remote-file" );\n  // process inputstream as needed\n\nsftpChannel.exit();\nsession.disconnect();\n</code></pre>\n'}, {'answer_id': 16851, 'author': 'Boris Terzic', 'author_id': 1996, 'author_profile': 'https://Stackoverflow.com/users/1996', 'pm_score': 5, 'selected': False, 'text': '<p>A nice abstraction on top of Jsch is Apache <a href="http://commons.apache.org/vfs/" rel="noreferrer">commons-vfs</a> which offers a virtual filesystem API that makes accessing and writing SFTP files almost transparent. Worked well for us.</p>\n'}, {'answer_id': 433052, 'author': 'Brian Clapper', 'author_id': 53495, 'author_profile': 'https://Stackoverflow.com/users/53495', 'pm_score': 0, 'selected': False, 'text': '<p>The best solution I\'ve found is <a href="http://www.lag.net/paramiko/" rel="nofollow noreferrer">Paramiko</a>. There\'s a Java version.</p>\n'}, {'answer_id': 548977, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>You also have JFileUpload with SFTP add-on (Java too):\n<a href="http://www.jfileupload.com/products/sftp/index.html" rel="nofollow noreferrer">http://www.jfileupload.com/products/sftp/index.html</a></p>\n'}, {'answer_id': 915030, 'author': 'Bruce Blackshaw', 'author_id': 109114, 'author_profile': 'https://Stackoverflow.com/users/109114', 'pm_score': 2, 'selected': False, 'text': '<p>Try <a href="http://www.enterprisedt.com/products/edtftpjssl/overview.html" rel="nofollow noreferrer">edtFTPj/PRO</a>, a mature, robust SFTP client library that supports connection pools and asynchronous operations. Also supports FTP and FTPS so all bases for secure file transfer are covered.</p>\n'}, {'answer_id': 1011405, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 1, 'selected': False, 'text': '<p>I use this SFTP API called Zehon, it\'s great, so easy to use with a lot of sample code. Here is the site <a href="http://www.zehon.com" rel="nofollow noreferrer">http://www.zehon.com</a></p>\n'}, {'answer_id': 2404783, 'author': 'shikhar', 'author_id': 126346, 'author_profile': 'https://Stackoverflow.com/users/126346', 'pm_score': 3, 'selected': False, 'text': '<p><a href="https://github.com/hierynomus/sshj" rel="nofollow noreferrer">hierynomus/sshj</a> has a complete implementation of SFTP version 3 (what OpenSSH implements)</p>\n\n<p>Example code from <a href="https://github.com/hierynomus/sshj/blob/master/examples/src/main/java/net/schmizz/sshj/examples/SFTPUpload.java" rel="nofollow noreferrer">SFTPUpload.java</a></p>\n\n<pre><code>package net.schmizz.sshj.examples;\n\nimport net.schmizz.sshj.SSHClient;\nimport net.schmizz.sshj.sftp.SFTPClient;\nimport net.schmizz.sshj.xfer.FileSystemFile;\n\nimport java.io.File;\nimport java.io.IOException;\n\n/** This example demonstrates uploading of a file over SFTP to the SSH server. */\npublic class SFTPUpload {\n\n    public static void main(String[] args)\n            throws IOException {\n        final SSHClient ssh = new SSHClient();\n        ssh.loadKnownHosts();\n        ssh.connect("localhost");\n        try {\n            ssh.authPublickey(System.getProperty("user.name"));\n            final String src = System.getProperty("user.home") + File.separator + "test_file";\n            final SFTPClient sftp = ssh.newSFTPClient();\n            try {\n                sftp.put(new FileSystemFile(src), "/tmp");\n            } finally {\n                sftp.close();\n            }\n        } finally {\n            ssh.disconnect();\n        }\n    }\n\n}\n</code></pre>\n'}, {'answer_id': 2548590, 'author': 'Chris J', 'author_id': 165119, 'author_profile': 'https://Stackoverflow.com/users/165119', 'pm_score': 6, 'selected': False, 'text': '<p>Below is an example using Apache Common VFS:</p>\n\n<pre><code>FileSystemOptions fsOptions = new FileSystemOptions();\nSftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(fsOptions, "no");\nFileSystemManager fsManager = VFS.getManager();\nString uri = "sftp://user:password@host:port/absolute-path";\nFileObject fo = fsManager.resolveFile(uri, fsOptions);\n</code></pre>\n'}, {'answer_id': 2690861, 'author': 'Iraklis', 'author_id': 172467, 'author_profile': 'https://Stackoverflow.com/users/172467', 'pm_score': 7, 'selected': False, 'text': '<p>Here is the complete source code of an example using <a href="http://www.jcraft.com/jsch/" rel="noreferrer">JSch</a> without having to worry about the ssh key checking.</p>\n\n<pre><code>import com.jcraft.jsch.*;\n\npublic class TestJSch {\n    public static void main(String args[]) {\n        JSch jsch = new JSch();\n        Session session = null;\n        try {\n            session = jsch.getSession("username", "127.0.0.1", 22);\n            session.setConfig("StrictHostKeyChecking", "no");\n            session.setPassword("password");\n            session.connect();\n\n            Channel channel = session.openChannel("sftp");\n            channel.connect();\n            ChannelSftp sftpChannel = (ChannelSftp) channel;\n            sftpChannel.get("remotefile.txt", "localfile.txt");\n            sftpChannel.exit();\n            session.disconnect();\n        } catch (JSchException e) {\n            e.printStackTrace();  \n        } catch (SftpException e) {\n            e.printStackTrace();\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 4728735, 'author': 'Dee Kay', 'author_id': 580515, 'author_profile': 'https://Stackoverflow.com/users/580515', 'pm_score': 2, 'selected': False, 'text': '<p>I found complete working example for SFTP in java using JSCH API \n<a href="http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/" rel="nofollow">http://kodehelp.com/java-program-for-uploading-file-to-sftp-server/</a></p>\n'}, {'answer_id': 5229795, 'author': 'Pushpinder Rattan', 'author_id': 480686, 'author_profile': 'https://Stackoverflow.com/users/480686', 'pm_score': 2, 'selected': False, 'text': '<p>Andy, to delete file on remote system you need to use <code>(channelExec)</code> of JSch and pass unix/linux commands to delete it.</p>\n'}, {'answer_id': 18005722, 'author': 'Zon', 'author_id': 1112963, 'author_profile': 'https://Stackoverflow.com/users/1112963', 'pm_score': 2, 'selected': False, 'text': '<p>Though answers above were very helpful, I\'ve spent a day to make them work, facing various exceptions like "broken channel", "rsa key unknown" and "packet corrupt".</p>\n\n<p>Below is a working reusable class for SFTP FILES UPLOAD/DOWNLOAD using JSch library.</p>\n\n<p>Upload usage:</p>\n\n<pre><code>SFTPFileCopy upload = new SFTPFileCopy(true, /path/to/sourcefile.png", /path/to/destinationfile.png");\n</code></pre>\n\n<p>Download usage:</p>\n\n<pre><code>SFTPFileCopy download = new SFTPFileCopy(false, "/path/to/sourcefile.png", "/path/to/destinationfile.png");\n</code></pre>\n\n<p>The class code:</p>\n\n<pre><code>import com.jcraft.jsch.Channel;\nimport com.jcraft.jsch.ChannelSftp;\nimport com.jcraft.jsch.JSch;\nimport com.jcraft.jsch.Session;\nimport com.jcraft.jsch.UIKeyboardInteractive;\nimport com.jcraft.jsch.UserInfo;\nimport java.io.BufferedInputStream;\nimport java.io.BufferedOutputStream;\nimport java.io.ByteArrayInputStream;\nimport java.io.File;\nimport java.io.FileInputStream;\nimport java.io.FileNotFoundException;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.io.OutputStream;\nimport javax.swing.JOptionPane;\nimport menue.Menue;\n\npublic class SFTPFileCopy1 {\n\n    public SFTPFileCopy1(boolean upload, String sourcePath, String destPath) throws FileNotFoundException, IOException {\n        Session session = null;\n        Channel channel = null;\n        ChannelSftp sftpChannel = null;\n        try {\n            JSch jsch = new JSch();\n            //jsch.setKnownHosts("/home/user/.putty/sshhostkeys");\n            session = jsch.getSession("login", "mysite.com", 22);\n            session.setPassword("password");\n\n            UserInfo ui = new MyUserInfo() {\n                public void showMessage(String message) {\n\n                    JOptionPane.showMessageDialog(null, message);\n\n                }\n\n                public boolean promptYesNo(String message) {\n\n                    Object[] options = {"yes", "no"};\n\n                    int foo = JOptionPane.showOptionDialog(null,\n                            message,\n                            "Warning",\n                            JOptionPane.DEFAULT_OPTION,\n                            JOptionPane.WARNING_MESSAGE,\n                            null, options, options[0]);\n\n                    return foo == 0;\n\n                }\n            };\n            session.setUserInfo(ui);\n\n            session.setConfig("StrictHostKeyChecking", "no");\n            session.connect();\n            channel = session.openChannel("sftp");\n            channel.setInputStream(System.in);\n            channel.setOutputStream(System.out);\n            channel.connect();\n            sftpChannel = (ChannelSftp) channel;\n\n            if (upload) { // File upload.\n                byte[] bufr = new byte[(int) new File(sourcePath).length()];\n                FileInputStream fis = new FileInputStream(new File(sourcePath));\n                fis.read(bufr);\n                ByteArrayInputStream fileStream = new ByteArrayInputStream(bufr);\n                sftpChannel.put(fileStream, destPath);\n                fileStream.close();\n            } else { // File download.\n                byte[] buffer = new byte[1024];\n                BufferedInputStream bis = new BufferedInputStream(sftpChannel.get(sourcePath));\n                OutputStream os = new FileOutputStream(new File(destPath));\n                BufferedOutputStream bos = new BufferedOutputStream(os);\n                int readCount;\n                while ((readCount = bis.read(buffer)) &gt; 0) {\n                    bos.write(buffer, 0, readCount);\n                }\n                bis.close();\n                bos.close();\n            }\n        } catch (Exception e) {\n            System.out.println(e);\n        } finally {\n            if (sftpChannel != null) {\n                sftpChannel.exit();\n            }\n            if (channel != null) {\n                channel.disconnect();\n            }\n            if (session != null) {\n                session.disconnect();\n            }\n        }\n    }\n\n    public static abstract class MyUserInfo\n            implements UserInfo, UIKeyboardInteractive {\n\n        public String getPassword() {\n            return null;\n        }\n\n        public boolean promptYesNo(String str) {\n            return false;\n        }\n\n        public String getPassphrase() {\n            return null;\n        }\n\n        public boolean promptPassphrase(String message) {\n            return false;\n        }\n\n        public boolean promptPassword(String message) {\n            return false;\n        }\n\n        public void showMessage(String message) {\n        }\n\n        public String[] promptKeyboardInteractive(String destination,\n                String name,\n                String instruction,\n                String[] prompt,\n                boolean[] echo) {\n\n            return null;\n        }\n    }\n}\n</code></pre>\n'}, {'answer_id': 18975867, 'author': 'AZ_', 'author_id': 185022, 'author_profile': 'https://Stackoverflow.com/users/185022', 'pm_score': 4, 'selected': False, 'text': '<p>See <a href="http://www.mysamplecode.com/2013/06/sftp-apache-commons-file-download.html" rel="nofollow noreferrer">http://www.mysamplecode.com/2013/06/sftp-apache-commons-file-download.html</a></p>\n<blockquote>\n<p>Apache Commons SFTP library</p>\n</blockquote>\n<p><strong>Common java properties file for all the examples</strong></p>\n<p>serverAddress=111.222.333.444</p>\n<p>userId=myUserId</p>\n<p>password=myPassword</p>\n<p>remoteDirectory=products/</p>\n<p>localDirectory=import/</p>\n<blockquote>\n<p>Upload file to remote server using SFTP</p>\n</blockquote>\n<pre><code>import java.io.File;\nimport java.io.FileInputStream;\nimport java.util.Properties;\n \nimport org.apache.commons.vfs2.FileObject;\nimport org.apache.commons.vfs2.FileSystemOptions;\nimport org.apache.commons.vfs2.Selectors;\nimport org.apache.commons.vfs2.impl.StandardFileSystemManager;\nimport org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;\n \npublic class SendMyFiles {\n \n static Properties props;\n \n public static void main(String[] args) {\n \n  SendMyFiles sendMyFiles = new SendMyFiles();\n  if (args.length &lt; 1)\n  {\n   System.err.println(&quot;Usage: java &quot; + sendMyFiles.getClass().getName()+\n     &quot; Properties_file File_To_FTP &quot;);\n   System.exit(1);\n  }\n \n  String propertiesFile = args[0].trim();\n  String fileToFTP = args[1].trim();\n  sendMyFiles.startFTP(propertiesFile, fileToFTP);\n \n }\n \n public boolean startFTP(String propertiesFilename, String fileToFTP){\n \n  props = new Properties();\n  StandardFileSystemManager manager = new StandardFileSystemManager();\n \n  try {\n \n   props.load(new FileInputStream(&quot;properties/&quot; + propertiesFilename));\n   String serverAddress = props.getProperty(&quot;serverAddress&quot;).trim();\n   String userId = props.getProperty(&quot;userId&quot;).trim();\n   String password = props.getProperty(&quot;password&quot;).trim();\n   String remoteDirectory = props.getProperty(&quot;remoteDirectory&quot;).trim();\n   String localDirectory = props.getProperty(&quot;localDirectory&quot;).trim();\n \n   //check if the file exists\n   String filepath = localDirectory +  fileToFTP;\n   File file = new File(filepath);\n   if (!file.exists())\n    throw new RuntimeException(&quot;Error. Local file not found&quot;);\n \n   //Initializes the file manager\n   manager.init();\n    \n   //Setup our SFTP configuration\n   FileSystemOptions opts = new FileSystemOptions();\n   SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(\n     opts, &quot;no&quot;);\n   SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);\n   SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);\n    \n   //Create the SFTP URI using the host name, userid, password,  remote path and file name\n   String sftpUri = &quot;sftp://&quot; + userId + &quot;:&quot; + password +  &quot;@&quot; + serverAddress + &quot;/&quot; + \n     remoteDirectory + fileToFTP;\n    \n   // Create local file object\n   FileObject localFile = manager.resolveFile(file.getAbsolutePath());\n \n   // Create remote file object\n   FileObject remoteFile = manager.resolveFile(sftpUri, opts);\n \n   // Copy local file to sftp server\n   remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);\n   System.out.println(&quot;File upload successful&quot;);\n \n  }\n  catch (Exception ex) {\n   ex.printStackTrace();\n   return false;\n  }\n  finally {\n   manager.close();\n  }\n \n  return true;\n }\n \n  \n}\n</code></pre>\n<blockquote>\n<p>Download file from remote server using SFTP</p>\n</blockquote>\n<pre><code>import java.io.File;\nimport java.io.FileInputStream;\nimport java.util.Properties;\n \nimport org.apache.commons.vfs2.FileObject;\nimport org.apache.commons.vfs2.FileSystemOptions;\nimport org.apache.commons.vfs2.Selectors;\nimport org.apache.commons.vfs2.impl.StandardFileSystemManager;\nimport org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;\n \npublic class GetMyFiles {\n \n static Properties props;\n \n public static void main(String[] args) {\n \n  GetMyFiles getMyFiles = new GetMyFiles();\n  if (args.length &lt; 1)\n  {\n   System.err.println(&quot;Usage: java &quot; + getMyFiles.getClass().getName()+\n   &quot; Properties_filename File_To_Download &quot;);\n   System.exit(1);\n  }\n \n  String propertiesFilename = args[0].trim();\n  String fileToDownload = args[1].trim();\n  getMyFiles.startFTP(propertiesFilename, fileToDownload);\n    \n }\n \n public boolean startFTP(String propertiesFilename, String fileToDownload){\n \n  props = new Properties();\n  StandardFileSystemManager manager = new StandardFileSystemManager();\n \n  try {\n \n   props.load(new FileInputStream(&quot;properties/&quot; + propertiesFilename));\n   String serverAddress = props.getProperty(&quot;serverAddress&quot;).trim();\n   String userId = props.getProperty(&quot;userId&quot;).trim();\n   String password = props.getProperty(&quot;password&quot;).trim();\n   String remoteDirectory = props.getProperty(&quot;remoteDirectory&quot;).trim();\n   String localDirectory = props.getProperty(&quot;localDirectory&quot;).trim();\n \n    \n   //Initializes the file manager\n   manager.init();\n    \n   //Setup our SFTP configuration\n   FileSystemOptions opts = new FileSystemOptions();\n   SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(\n     opts, &quot;no&quot;);\n   SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);\n   SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);\n    \n   //Create the SFTP URI using the host name, userid, password,  remote path and file name\n   String sftpUri = &quot;sftp://&quot; + userId + &quot;:&quot; + password +  &quot;@&quot; + serverAddress + &quot;/&quot; + \n     remoteDirectory + fileToDownload;\n    \n   // Create local file object\n   String filepath = localDirectory +  fileToDownload;\n   File file = new File(filepath);\n   FileObject localFile = manager.resolveFile(file.getAbsolutePath());\n \n   // Create remote file object\n   FileObject remoteFile = manager.resolveFile(sftpUri, opts);\n \n   // Copy local file to sftp server\n   localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);\n   System.out.println(&quot;File download successful&quot;);\n \n  }\n  catch (Exception ex) {\n   ex.printStackTrace();\n   return false;\n  }\n  finally {\n   manager.close();\n  }\n \n  return true;\n }\n \n}\n</code></pre>\n<blockquote>\n<p>Delete a file on remote server using SFTP</p>\n</blockquote>\n<pre><code>import java.io.FileInputStream;\nimport java.util.Properties;\n \nimport org.apache.commons.vfs2.FileObject;\nimport org.apache.commons.vfs2.FileSystemOptions;\nimport org.apache.commons.vfs2.impl.StandardFileSystemManager;\nimport org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;\n \npublic class DeleteRemoteFile {\n \n static Properties props;\n \n public static void main(String[] args) {\n \n  DeleteRemoteFile getMyFiles = new DeleteRemoteFile();\n  if (args.length &lt; 1)\n  {\n   System.err.println(&quot;Usage: java &quot; + getMyFiles.getClass().getName()+\n   &quot; Properties_filename File_To_Delete &quot;);\n   System.exit(1);\n  }\n \n  String propertiesFilename = args[0].trim();\n  String fileToDownload = args[1].trim();\n  getMyFiles.startFTP(propertiesFilename, fileToDownload);\n    \n }\n \n public boolean startFTP(String propertiesFilename, String fileToDownload){\n \n  props = new Properties();\n  StandardFileSystemManager manager = new StandardFileSystemManager();\n \n  try {\n \n   props.load(new FileInputStream(&quot;properties/&quot; + propertiesFilename));\n   String serverAddress = props.getProperty(&quot;serverAddress&quot;).trim();\n   String userId = props.getProperty(&quot;userId&quot;).trim();\n   String password = props.getProperty(&quot;password&quot;).trim();\n   String remoteDirectory = props.getProperty(&quot;remoteDirectory&quot;).trim();\n    \n    \n   //Initializes the file manager\n   manager.init();\n    \n   //Setup our SFTP configuration\n   FileSystemOptions opts = new FileSystemOptions();\n   SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(\n     opts, &quot;no&quot;);\n   SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);\n   SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);\n    \n   //Create the SFTP URI using the host name, userid, password,  remote path and file name\n   String sftpUri = &quot;sftp://&quot; + userId + &quot;:&quot; + password +  &quot;@&quot; + serverAddress + &quot;/&quot; + \n     remoteDirectory + fileToDownload;\n    \n   //Create remote file object\n   FileObject remoteFile = manager.resolveFile(sftpUri, opts);\n \n   //Check if the file exists\n   if(remoteFile.exists()){\n    remoteFile.delete();\n    System.out.println(&quot;File delete successful&quot;);\n   }\n   \n  }\n  catch (Exception ex) {\n   ex.printStackTrace();\n   return false;\n  }\n  finally {\n   manager.close();\n  }\n \n  return true;\n }\n \n}\n</code></pre>\n'}, {'answer_id': 36422906, 'author': 'Sasha', 'author_id': 91495, 'author_profile': 'https://Stackoverflow.com/users/91495', 'pm_score': 5, 'selected': False, 'text': '<p>There is a nice comparison of the 3 mature Java libraries for SFTP: <a href="https://www.javacodegeeks.com/2015/08/commons-vfs-sshj-and-jsch-in-comparison.html" rel="noreferrer">Commons VFS, SSHJ and JSch</a> </p>\n\n<p>To sum up SSHJ has the clearest API and it\'s the best out of them if you don\'t need other storages support provided by Commons VFS.</p>\n\n<p>Here is edited SSHJ example from <a href="https://github.com/hierynomus/sshj/blob/master/examples/src/main/java/net/schmizz/sshj/examples/SFTPDownload.java" rel="noreferrer">github</a>:</p>\n\n<pre><code>final SSHClient ssh = new SSHClient();\nssh.loadKnownHosts(); // or, to skip host verification: ssh.addHostKeyVerifier(new PromiscuousVerifier())\nssh.connect("localhost");\ntry {\n    ssh.authPassword("user", "password"); // or ssh.authPublickey(System.getProperty("user.name"))\n    final SFTPClient sftp = ssh.newSFTPClient();\n    try {\n        sftp.get("test_file", "/tmp/test.tmp");\n    } finally {\n        sftp.close();\n    }\n} finally {\n    ssh.disconnect();\n}\n</code></pre>\n'}, {'answer_id': 46559783, 'author': 'Ankur jain', 'author_id': 641001, 'author_profile': 'https://Stackoverflow.com/users/641001', 'pm_score': 3, 'selected': False, 'text': '<p>JSch library is the powerful library that can be used to read file from SFTP server. Below is the tested code to read file from SFTP location line by line</p>\n\n<pre><code>JSch jsch = new JSch();\n        Session session = null;\n        try {\n            session = jsch.getSession("user", "127.0.0.1", 22);\n            session.setConfig("StrictHostKeyChecking", "no");\n            session.setPassword("password");\n            session.connect();\n\n            Channel channel = session.openChannel("sftp");\n            channel.connect();\n            ChannelSftp sftpChannel = (ChannelSftp) channel;\n\n            InputStream stream = sftpChannel.get("/usr/home/testfile.txt");\n            try {\n                BufferedReader br = new BufferedReader(new InputStreamReader(stream));\n                String line;\n                while ((line = br.readLine()) != null) {\n                    System.out.println(line);\n                }\n\n            } catch (IOException io) {\n                System.out.println("Exception occurred during reading file from SFTP server due to " + io.getMessage());\n                io.getMessage();\n\n            } catch (Exception e) {\n                System.out.println("Exception occurred during reading file from SFTP server due to " + e.getMessage());\n                e.getMessage();\n\n            }\n\n            sftpChannel.exit();\n            session.disconnect();\n        } catch (JSchException e) {\n            e.printStackTrace();\n        } catch (SftpException e) {\n            e.printStackTrace();\n        }\n</code></pre>\n\n<p>Please refer the <a href="https://ankurjain26.blogspot.in/2017/09/reading-file-from-remote-server-using.html" rel="noreferrer">blog</a> for whole program.</p>\n'}]
['https://Stackoverflow.com/questions/14617', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1769/']