Java SFTP Apache commons file download, upload and delete example

Secure File Transfer Protocol or SFTP uses the SSH secure shell protocol to provides file access, file transfer, and file management functionalities over any reliable data stream. Apache Commons VFS provides a single API for accessing various different file systems and one of them is SFTP. Here are the examples for how to use the VFS to achieve file download, upload and delete on a remote system. Before you copy the sources please go ahead and download the following jar files and place them in your classpath.

Common java properties file for all the examples

serverAddress=111.222.333.444
userId=myUserId
password=myPassword
remoteDirectory=products/                        
localDirectory=import/

Upload file to remote server using SFTP

package com.as400samplecode;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;

public class SendMyFiles {

 static Properties props;

 public static void main(String[] args) {

  SendMyFiles sendMyFiles = new SendMyFiles();
  if (args.length < 1)
  {
   System.err.println("Usage: java " + sendMyFiles.getClass().getName()+
     " Properties_file File_To_FTP ");
   System.exit(1);
  }

  String propertiesFile = args[0].trim();
  String fileToFTP = args[1].trim();
  sendMyFiles.startFTP(propertiesFile, fileToFTP);

 }

 public boolean startFTP(String propertiesFilename, String fileToFTP){

  props = new Properties();
  StandardFileSystemManager manager = new StandardFileSystemManager();

  try {

   props.load(new FileInputStream("properties/" + propertiesFilename));
   String serverAddress = props.getProperty("serverAddress").trim();
   String userId = props.getProperty("userId").trim();
   String password = props.getProperty("password").trim();
   String remoteDirectory = props.getProperty("remoteDirectory").trim();
   String localDirectory = props.getProperty("localDirectory").trim();

   //check if the file exists
   String filepath = localDirectory +  fileToFTP;
   File file = new File(filepath);
   if (!file.exists())
    throw new RuntimeException("Error. Local file not found");

   //Initializes the file manager
   manager.init();
   
   //Setup our SFTP configuration
   FileSystemOptions opts = new FileSystemOptions();
   SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
     opts, "no");
   SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
   SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
   
   //Create the SFTP URI using the host name, userid, password,  remote path and file name
   String sftpUri = "sftp://" + userId + ":" + password +  "@" + serverAddress + "/" + 
     remoteDirectory + fileToFTP;
   
   // Create local file object
   FileObject localFile = manager.resolveFile(file.getAbsolutePath());

   // Create remote file object
   FileObject remoteFile = manager.resolveFile(sftpUri, opts);

   // Copy local file to sftp server
   remoteFile.copyFrom(localFile, Selectors.SELECT_SELF);
   System.out.println("File upload successful");

  }
  catch (Exception ex) {
   ex.printStackTrace();
   return false;
  }
  finally {
   manager.close();
  }

  return true;
 }

 
}

Download file from remote server using SFTP

package com.as400samplecode;

import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;

public class GetMyFiles {

 static Properties props;

 public static void main(String[] args) {

  GetMyFiles getMyFiles = new GetMyFiles();
  if (args.length < 1)
  {
   System.err.println("Usage: java " + getMyFiles.getClass().getName()+
   " Properties_filename File_To_Download ");
   System.exit(1);
  }

  String propertiesFilename = args[0].trim();
  String fileToDownload = args[1].trim();
  getMyFiles.startFTP(propertiesFilename, fileToDownload);
   
 }

 public boolean startFTP(String propertiesFilename, String fileToDownload){

  props = new Properties();
  StandardFileSystemManager manager = new StandardFileSystemManager();

  try {

   props.load(new FileInputStream("properties/" + propertiesFilename));
   String serverAddress = props.getProperty("serverAddress").trim();
   String userId = props.getProperty("userId").trim();
   String password = props.getProperty("password").trim();
   String remoteDirectory = props.getProperty("remoteDirectory").trim();
   String localDirectory = props.getProperty("localDirectory").trim();

   
   //Initializes the file manager
   manager.init();
   
   //Setup our SFTP configuration
   FileSystemOptions opts = new FileSystemOptions();
   SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
     opts, "no");
   SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
   SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
   
   //Create the SFTP URI using the host name, userid, password,  remote path and file name
   String sftpUri = "sftp://" + userId + ":" + password +  "@" + serverAddress + "/" + 
     remoteDirectory + fileToDownload;
   
   // Create local file object
   String filepath = localDirectory +  fileToDownload;
   File file = new File(filepath);
   FileObject localFile = manager.resolveFile(file.getAbsolutePath());

   // Create remote file object
   FileObject remoteFile = manager.resolveFile(sftpUri, opts);

   // Copy local file to sftp server
   localFile.copyFrom(remoteFile, Selectors.SELECT_SELF);
   System.out.println("File download successful");

  }
  catch (Exception ex) {
   ex.printStackTrace();
   return false;
  }
  finally {
   manager.close();
  }

  return true;
 }

}

Delete a file on remote server using SFTP

package com.as400samplecode;

import java.io.FileInputStream;
import java.util.Properties;

import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;

public class DeleteRemoteFile {

 static Properties props;

 public static void main(String[] args) {

  DeleteRemoteFile getMyFiles = new DeleteRemoteFile();
  if (args.length < 1)
  {
   System.err.println("Usage: java " + getMyFiles.getClass().getName()+
   " Properties_filename File_To_Delete ");
   System.exit(1);
  }

  String propertiesFilename = args[0].trim();
  String fileToDownload = args[1].trim();
  getMyFiles.startFTP(propertiesFilename, fileToDownload);
   
 }

 public boolean startFTP(String propertiesFilename, String fileToDownload){

  props = new Properties();
  StandardFileSystemManager manager = new StandardFileSystemManager();

  try {

   props.load(new FileInputStream("properties/" + propertiesFilename));
   String serverAddress = props.getProperty("serverAddress").trim();
   String userId = props.getProperty("userId").trim();
   String password = props.getProperty("password").trim();
   String remoteDirectory = props.getProperty("remoteDirectory").trim();
   
   
   //Initializes the file manager
   manager.init();
   
   //Setup our SFTP configuration
   FileSystemOptions opts = new FileSystemOptions();
   SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(
     opts, "no");
   SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
   SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);
   
   //Create the SFTP URI using the host name, userid, password,  remote path and file name
   String sftpUri = "sftp://" + userId + ":" + password +  "@" + serverAddress + "/" + 
     remoteDirectory + fileToDownload;
   
   //Create remote file object
   FileObject remoteFile = manager.resolveFile(sftpUri, opts);

   //Check if the file exists
   if(remoteFile.exists()){
    remoteFile.delete();
    System.out.println("File delete successful");
   }
  
  }
  catch (Exception ex) {
   ex.printStackTrace();
   return false;
  }
  finally {
   manager.close();
  }

  return true;
 }

}

92 comments :

  1. Thanks for the post. Worked great for me. I am newbie to this stuff.

    ReplyDelete
    Replies
    1. Many thanks for sharing here examples for how to use the VFS to achieve file download, upload and delete on a remote system which are very useful information for IT students who are taking College dissertation writing services from me and looking for such kind of information at Quality Assignment UK which is UK’s best dissertation writing services provider consultancy where I am now working as a dissertation tutor. Thanks. Keep sharing.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete
  3. How I can create the file properties in eclipse kepler for your example?

    ReplyDelete
  4. This is a great post. I have to set the file permissions after I upload the file. How can I do this in vfs2.0. Appreciate your help with this.

    ReplyDelete
  5. Is "remoteDirectory=products/" a relative path? how can I construct a absolute pathDirectory?

    Thank you

    ReplyDelete
  6. Gratefulness touches deeply the tenderness fifa 14 coins of my heart, rendering me ever-profound perception cheap fifa 14 coins as well as ever-soft emotion. It is like the soft melody of “ kiss the rain”, so tender, so emotional fifa 14 coins and so fascinating, leaving me out of all the worldly troubles.

    ReplyDelete
  7. Hi, please help me in executing the project i couldn't get the proper output. please temme how to create properties files and where i have to place it in eclipse?
    thanks in advance.

    ReplyDelete
  8. Hi, How can i monitor the status of the upload/download. My requirement is to write one more thread which should monitor the upload/download status. I mean the thread should print like( download 1% completed...2% completed.......100% completed). Any help is much appreciated.

    ReplyDelete
  9. Hello ,

    I am using file.exists() method. This method is not working for remore path

    Path should be like this : https://files.schoolcity.com/items/temp.pdf

    Thanks,
    Sathish.H

    ReplyDelete
  10. EXCELLENT information. Your directions are clear and concise, and easy to follow. Thanks for your hard work in posting this info.

    ReplyDelete
  11. What is value i have pass for propertiesfile

    ReplyDelete
  12. Good. But, according to the source above, It seems that jsch is not needed.

    ReplyDelete
    Replies
    1. try to remove the jsch.jar and you'll see that SFTP won't work

      Delete
  13. how to connect via sftp keys.?

    ReplyDelete
  14. Nice post!
    How can I get all the files in the remote folder?
    Thanks!

    ReplyDelete
    Replies
    1. FileObject remoteFolder = manager.resolveFile(sftpUri1, opts);

      localfolder.copyFrom(remoteFolder, Selectors.SELECT_CHILDREN);

      Delete
  15. Download works great, thanks! Uploading new file into existing directory fails with org.apache.commons.vfs2.FileSystemException: Could not create folder "sftp://test:***@ipaddress/advs" because it already exists and is a file. Any ideas?

    ReplyDelete
  16. đồng tâm
    game mu
    cho thuê nhà trọ
    cho thuê phòng trọ
    nhac san cuc manh
    số điện thoại tư vấn pháp luật miễn phí
    văn phòng luật
    tổng đài tư vấn pháp luật
    dịch vụ thành lập công ty trọn gói

    Trong nội tâm Mạnh Siêu Nhiên, mặc dù vì việc này cảm thấy vô cùng phẫn nộ, nhưng ngược lại cũng vì Sở Dương khéo hiểu lòng người mà cảm thấy vui mừng.

    Sở Dương khẽ gật đầu, bưng lên khay đồ ăn đã chuẩn bị trước cho Thạch Thiên Sơn bước ra. Tới phòng của Thạch Thiên Sơn, hắn nửa cười nửa không nói:
    - Đại sư huynh, ăn cơm thôi.

    - Không phải Đàm Đàm vẫn luôn đưa cơm cho huynh à? Hôm nay sao lại là đệ thế?
    Thạch Thiên Sơn nghi hoặc nhìn Sở Dương, hỏi.

    - Cái tên Đàm Đàm kia hôm nay mệt không dậy nổi rồi.
    Sở Dương mỉm cười thân thiện:
    - Ba sư huynh đệ chúng ta, dù là đệ đến hay là Đàm Đàm đến thì chẳng phải là cũng giống nhau sao? Thời gian vừa qua đại sư huynh hết lòng giúp đỡ bọn đệ như vậy, thực sự là tình thâm nghĩa trọng, tiểu đệ nghĩ mình cũng nên làm gì đó báo đáp huynh.

    Thạch Thiên Sơn hừ một tiếng:
    - Hôm nay khẩu vị của ta không tốt lắm, không muốn ăn. Ngươi cứ để ở một bên đi.

    Nói đùa à, hắn biết rõ bên trong có độc, hơn nữa còn là tự tay hắn hạ độc, làm sao mà hắn dám ăn chứ?

    ReplyDelete
  17. excellent post, thanks, regards @OsmanGt1

    ReplyDelete
  18. good post but author seems not writing much anymore. thanks btw!

    ReplyDelete
  19. yup this articles really defined what i was looking for. Thanks for sharing e-commerce web

    ReplyDelete
  20. I am getting error while doing File Upload.
    org.apache.commons.vfs2.FileSystemException: Badly formed URI "sftp://username:***@server ip address/users/username/abcxyz.csv".
    at org.apache.commons.vfs2.provider.url.UrlFileProvider.findFile(UrlFileProvider.java:91)
    at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:713)
    at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveFile(DefaultFileSystemManager.java:621)
    at com.cisco.pmc.sftp.SendMyFiles.startFTP(SendMyFiles.java:72)
    at com.cisco.pmc.sftp.SendMyFiles.main(SendMyFiles.java:26)
    Caused by: java.net.MalformedURLException: unknown protocol: sftp
    at java.net.URL.(URL.java:592)
    at java.net.URL.(URL.java:482)
    at java.net.URL.(URL.java:431)
    at org.apache.commons.vfs2.provider.url.UrlFileProvider.findFile(UrlFileProvider.java:72).
    When i checked the file UrlFileProvider the method findFile() has three arguments,but in the sample code you have given only two arguments we are passing. Could some one please let me know what could be the issue and how to resolve.

    ReplyDelete
    Replies
    1. Hi. You need to add the jsch-0.1.50.jar in the project. I had the same error caused by this missing jar.

      Delete
  21. The company profile pdf is very easy to so fascinating, leaving me out of all the worldly troubles.

    ReplyDelete
  22. This program is not at all working..! Simply display the success message.

    ReplyDelete
    Replies
    1. I'm pretty sure your local path is not good at all

      Delete
  23. can you tell me how to get properties file and File_To_FTP

    ReplyDelete
  24. Hi, can you please let me know how to rename the existing file in remote directory?

    ReplyDelete
  25. Thank you very much for your post, it makes us have more and more discs in our life, So kind for you, I also hope you will make more and more excellent post and let’s more and more talk, thank you very much, dear.
    facebook lite |resignation letter|qr code generator

    ReplyDelete
  26. Thank you. It was was very helpful.

    ReplyDelete
  27. Amazing .. Thanks for giving me the useful information. I think I need it!
    happy wheels
    happy wheels demo
    play happy wheels
    happy wheels game

    ReplyDelete
  28. I got an error(org.apache.commons.vfs2.FileSystemException: Could not connect to SFTP server) using the upload. Anyone can help me? Thanks

    ReplyDelete
  29. We are really grateful for your blog post. You will find a lot of approaches after visiting your post. Great work : contact form | snapchat emoji

    ReplyDelete
  30. Let’s keep the best falsh games for your child! abc | slither io | pokemon go | wings.io | happy wheels | happy wheels the game free: are safe place to play the very best free games for kids!

    ReplyDelete
  31. I am really enjoying reading your well written Information. I have read your post carefully and relies that this is a very helpful for me
    happy wheels
    return man 3
    friv4school

    ReplyDelete
  32. I loved the way you discuss the topic great work thanks for the share Your informative post.
    HBS Case Studies Solutions

    ReplyDelete
  33. The code for uploading the files running fine I am getting only one issue that after going to the destination location it again creates sub folder in that location and then copy the file.There is multiple folders created.

    ReplyDelete
  34. Hi need to read the remote file into input stream. How can i do it ?

    ReplyDelete
  35. Caused by: org.apache.commons.vfs.FileSystemException: Could not connect to SFTP server at "reports.paypal.com".
    at org.apache.commons.vfs.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:214)
    at org.apache.commons.vfs.provider.sftp.SftpFileProvider.doCreateFileSystem(SftpFileProvider.java:90)
    ... 6 more
    Caused by: com.jcraft.jsch.JSchException: Auth fail
    at com.jcraft.jsch.Session.connect(Session.java:452)
    at com.jcraft.jsch.Session.connect(Session.java:150)
    at org.apache.commons.vfs.provider.sftp.SftpClientFactory.createConnection(SftpClientFactory.java:210)

    ReplyDelete
  36. The article you have shared here very awesome. I really like and appreciated your work. I read deeply your article, the points you have mentioned in this article are useful

    monkey go happy | superfighters 2 | bloons td | happy wheels 3

    ReplyDelete
  37. The game controls are shown just under . Movement mechanisms primarily include acceleration and tilting controls.
    five nights at freddy's 2 | five nights at freddy's 4 |
    fireboy and watergirl 2 | 2048 game | red ball 5 | age of war

    ReplyDelete
  38. It is useful when reading these articles, I have a few days to find these things. It too is excellent, very grateful for your profound contribution
    paypal sign up

    ReplyDelete
  39. I am so happy to read this. This is the kind of manual that needs to be given and not the random misinformation that's at the other blogs.
    Best Content Writing Services

    ReplyDelete
  40. Download don't work for me , I get error "could not copy" because I not exist

    ReplyDelete
    Replies
    1. Please help me to solve this error

      Delete
  41. Listing file is proper. But downloading shows error org.apache.commons.vfs2.FileSystemException: Could not copy because it does not exist.

    The SFTP URL is correct showing correct file name and SFTP path

    ReplyDelete
  42. @souvik - I bumped into this issue as well, the problem is.

    SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);

    So, every path MUST be relative to the home directory of the user.. set

    SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, false);

    if you want to use the full path.

    ReplyDelete
  43. I found lots of interesting information here.Great work. i like this blog
    fireboy watergirl
    Geometry Dash

    ReplyDelete

  44. Thanks for your marvelous posting! I quite enjoyed reading it, you happen to be a great author. I will remember to bookmark your blog and will eventually come back very soon. Go to best social plan for get more related topic. Have a nice evening!
    Situs BandarQ, Poker, Domino 99 Online Terpercaya & Situs Judi Bola Online Terbesar dan Terpercaya Indonesia

    ReplyDelete
  45. Thanks for sharing this quality information with us. I really enjoyed reading : girls go games | unblocked games

    ReplyDelete
  46. i am getting connection reset errors

    The Exception means that the socket was closed unexpectedly from the other side

    ReplyDelete
  47. I have been searching out for this similar kind of post for past a week and hardly came across this. Thank you very much and will look for more postings from you. I like play game five nights at freddy’s 4, game word cookies game , game word cookies answers , hotmail sign in and hotmail login, and u? I hope people visit my website.

    ReplyDelete
  48. This is such a great resource that you are providing and you give it away for free. I love
    seeing that understand the value of providing a quality resource for free.
    bloons tower defense 5

    ReplyDelete

  49. Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write.
    Thanks for sharing !
    tanki online 2 | game 2048 online

    ReplyDelete
  50. The blog or and best that is extremely useful to keep I can share the ideas of the future as this is really what I was looking for, I am very comfortable and pleased to come here. Thank you very much.
    animal jam | five nights at freddy's | hotmail login

    ReplyDelete
  51. nice article I am there and mainly many of us filmywap app are downloading the app because in this

    ReplyDelete
  52. I'm trying to use this code in a webstart. I mean jnlp but im getting the error java.lang.NoClassDefFoundError: org/apache/commons/vfs2/FileSystemOptions
    can someone help me with that

    ReplyDelete
  53. Thanks for your sharing! The information your share is very useful to me and many people are looking for them just like me! Thank you so much!

    ReplyDelete
  54. org.apache.commons.vfs2.FileSystemException: Could not copy "sftp://dummyname:***@serveraddress/dummy/xyz.xml" because it does not exist.

    > One it could be because of the jar version used
    > Second is because of the property

    ** SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);

    TroubleShoot :
    > First ensure, your authentication is successful
    > Next if you are using any folder apart from root basically (/) in remote, then u need to set

    setUserDirIsRoot(opts, false) --> This allows you to pick up any directory structure from root and allow you to download the file

    ReplyDelete
  55. The article you have shared here very good. This is really interesting information for me. Thanks for sharing!
    - gmail sign up

    ReplyDelete
  56. Thanks for your page! Your share information it helped me alot! I pray for you to be happy and successful in your life.

    ReplyDelete
  57. Interesting article! Thank you for sharing them! I hope you will continue to have similar posts to share with everyone! I believe a lot of people will be surprised to read this article!

    ReplyDelete
  58. This is great, you are good, i like your post and i still waiting our next post
    Bandar Ceme

    ReplyDelete
  59. Absolutely really Amazing Articel and good point in there.
    Thanks shared.
    Dominoqiu

    ReplyDelete
  60. Great post. I was checking continuously this blog and I am impressed!
    Very useful info specifically the last part :) I care for such info much.
    I was looking for this certain information for a very long time.
    Thank you and best of luck hotmail login | hotmail email login | hotmail account login

    ReplyDelete
  61. Interesting article! Thank you for sharing them! I hope you will continue to have similar posts to share with everyone! I believe a lot of people will be surprised to read this article!
    slither io

    ReplyDelete
  62. Thanks for your post! I believe there are many who feel the same satisfaction as I read this article! I hope you will continue to have such articles to share with everyone!
    windows movie maker

    ReplyDelete
  63. The information which you people are given are really good, These look really great.
    BandarQ

    ReplyDelete
  64. This is really very nice blog and so informative. Thanks a lot for sharing this article.
    BandarQQ

    ReplyDelete
  65. Thanks for the informations you shared!! I hope you will continue to have similar posts to share with everyone! I believe a lot of people will be surprised to read this article!
    abcya

    ReplyDelete
  66. Thank your share! I’m very happy to read this. This is the kind of manual that needs to be given and not the accidental misinformation that is at the other blogs. Appreciate your sharing this greatest doc!
    bloons tower defense 5

    ReplyDelete