How to retrieve a file from a server via SFTP?

后端 未结 16 1341
萌比男神i
萌比男神i 2020-11-22 07:48

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

16条回答
  •  醉话见心
    2020-11-22 08:31

    Apache Commons SFTP library

    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

    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

    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

    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;
     }
    
    }
    

提交回复
热议问题