Java SFTP Apache commons file download, upload and delete example

来源:互联网 发布:云计算体系结构 编辑:程序博客网 时间:2024/05/17 04:01
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. 
  • commons-logging-api-1.1.3.jar
    • http://commons.apache.org/proper/commons-logging/download_logging.cgi
  • commons-vfs2-2.0.jar
    • http://commons.apache.org/proper/commons-vfs/download_vfs.cgi
  • jsch-0.1.50.jar
    • http://www.jcraft.com/jsch/

Common java properties file for all the examples

serverAddress=111.222.333.444userId=myUserIdpassword=myPasswordremoteDirectory=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; }}
0 0
原创粉丝点击