java使用SFTP连接服务器下载,上传文件

package mocha.framework.util;
/*
* @author Xiehj
* @version 2019年10月28日 上午9:37:28
*/
import java.io.File;  
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;  
import java.util.Vector;

import org.apache.log4j.Logger;

import com.jcraft.jsch.Channel;  
import com.jcraft.jsch.ChannelSftp;  
import com.jcraft.jsch.JSch;  
import com.jcraft.jsch.Session;  
import com.jcraft.jsch.SftpException;  
  
public class SftpTools {  
  private static final Logger log = Logger.getLogger(SftpTools.class);
	
  Session sshSession;
  /** 
     * 链接sftp 
     *  
     * @param host 
     *            主机 
     * @param port 
     *            端口 
     * @param username 
     *            用户名 
     * @param password 
     *            密码 
     * @return 
     */  
    public ChannelSftp connect(String host, int port, String username,  
            String password) {  
        ChannelSftp sftp = null;  
        try {  
            JSch jsch = new JSch();  
            sshSession = jsch.getSession(username, host, port);  
            //log.info("Session创建成功");  
            sshSession.setPassword(password); 
            //log.info("密码输入成功");
            //sshSession.setConfig("kex","diffie-hellman-group1-sha1");
            Properties sshConfig = new Properties();  
            sshConfig.put("StrictHostKeyChecking", "no");
            //log.info("链接参数设置成功");
            sshSession.setConfig(sshConfig);  
            sshSession.connect();  
            //log.info("Session已连接");  
            Channel channel = sshSession.openChannel("sftp");  
            channel.connect();  
            sftp = (ChannelSftp) channel;  
            //log.info("连接到主机" + host);
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return sftp;  
    }  
  
    /** 
     * 文件重命名 
     *  
     * @param directory 目录 
     * @param oldname 旧文件名   
     * @param newname 新文件名 
     * @param sftp 
     */  
    public void renameFile(String directory, String oldname, String newname,  
            ChannelSftp sftp) {  
        try {  
            sftp.cd(directory);  
            sftp.rename(oldname, newname);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
  
    /** 
     * 文件上传 
     *  
     * @param directory 目录 
     * @param uploadFile 要上传的文件名 
     * @param sftp 
     */  
    public void upload(String directory, String uploadFile, ChannelSftp sftp) {  
        try {  
            sftp.cd(directory);  
            File file = new File(uploadFile);  
            sftp.put(new FileInputStream(file), file.getName());  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
    
    
    public void uploada(String directory,String sftpFileName,InputStream input, ChannelSftp sftp) throws SftpException{
      try {
        sftp.cd(directory);
        
    } catch (Exception e) {
    }
      sftp.put(input, sftpFileName);
    }
    /**
   * 将输入流的数据上传到sftp作为文件。文件完整路径=basePath+directory
   * 
   * @param basePath
   *            服务器的基础路径
   * @param directory
   *            上传到该目录
   * @param sftpFileName
   *            sftp端文件名
   * @param input
   *            输入流 throws SftpException
   */
  public boolean upload(String directory, String sftpFileName,
      InputStream input, ChannelSftp sftp) {
    boolean ret = false;
    try {
      // sftp.cd(basePath);
      sftp.cd(directory);
      ret = true;
    } catch (SftpException e) {
      // 目录不存在,则创建文件夹
      String[] dirs = directory.split("/");
      String tempPath = "";
      for (String dir : dirs) {
        if (null == dir || "".equals(dir))
          continue;
         tempPath+="/"+dir;
        //tempPath = dir;
        try {
          sftp.cd(tempPath);
          ret = true;
        } catch (SftpException ex) {
          try {
            sftp.mkdir(tempPath);
            sftp.cd(tempPath);
            ret = true;
          } catch (SftpException e1) {
            ret = false;
            return ret;
          } catch (Exception e1) {
            ret = false;
            return ret;
          }
        } catch (Exception e1) {
          ret = false;
          return ret;
        }
      }
      ret = true;
    } catch (Exception e1) {
      ret = false;
      return ret;
    }
 
    try {
      sftp.put(input, sftpFileName);// 上传文件
      ret = true;
    } catch (SftpException e) {
      ret = false;
    }
    return ret;
  }

  
    /** 
     * 文件下载 
     *  
     * @param directory 目录 
     * @param downloadFile 要下载文件名 
     * @param saveFile 保持的文件名 
     * @param sftp 
     */  
    public void download(String directory, String downloadFile,  
            String saveFile, ChannelSftp sftp) {  
        try {  
            sftp.cd(directory);  
            File file = new File(saveFile);  
            sftp.get(downloadFile, new FileOutputStream(file));  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }  
    /**   
     * 下载文件  
     * @param directory 下载目录  
     * @param downloadFile 下载的文件名  
     * @return 字节数组  
     */    
    public InputStream download(String directory, String downloadFile,ChannelSftp sftp) {
        if (directory != null && !"".equals(directory)) {    
            try {
        sftp.cd(directory);
        InputStream is = sftp.get(downloadFile);  
        return is;
      } catch (SftpException e) {
        e.printStackTrace();
      }    
        }  
        return null;
    } 
  
    /** 
     * 文件删除 
     *  
     * @param directory 目录 
     * @param deleteFile 要删除的文件名 
     * @param sftp 
     */  
    public void delete(String directory, String deleteFile, ChannelSftp sftp) {  
        try {  
            sftp.cd(directory);  
            sftp.rm(deleteFile);  
            log.info("删除成功");  
        } catch (Exception e) {  
            log.info("删除失败");  
            e.printStackTrace();  
        }  
    }  
  
    /** 
     * 列出目录下的文件 
     *  
     * @param directory 目录 
     * @param sftp 
     * @return 
     * @throws SftpException 
     */  
    public Vector listFiles(String directory, ChannelSftp sftp)  
            throws SftpException {  
        return sftp.ls(directory);  
    }  
  
    
    //批量删除文件
  public void delete(String directory, String[] fileNames, ChannelSftp aa) {
    for (String fileName : fileNames) {
      this.delete(directory, fileName, aa);
    }
  }
  
  /**
   * 创建目录文件夹
   * @param directory  要创建文件夹的位置路径
   * @param fileName  要创建文件夹的名称
   * @param sftp   sftp连接
   */
  //创建目录文件
  public void mkdir(String directory,String fileName,ChannelSftp sftp){
        try {  
            sftp.cd(directory);  
            sftp.mkdir(fileName);  
            log.info("文件夹创建成功");  
        } catch (Exception e) {  
            log.info("文件夹创建失败");  
            e.printStackTrace();  
        }  
  }
  
  
   public static void downLoadPic(String path,String downLoadFileName,String newFileName){
        
      SftpTools sftpTools = new SftpTools();
      //测试环境地址
      String host="10.1.1.105";
      int port=22;
      String username="weblogic";
      String password="1232343";
      String directory="/weblogic/wls1036_x64/user_projects/domains/sasdomain/app/zyx_server/images/showpic/";    
      //建立sftp连接
      ChannelSftp content= sftpTools.connect(host, port, username, password);
      String saveFile = newFileName;
      //下载文件
      sftpTools.download(directory, downLoadFileName, saveFile, content);  
        
      } 
   
   /** 
       * 关闭连接 server  
       */   
      public void logout(ChannelSftp sftp){   
          if (sftp != null) {   
              if (sftp.isConnected()) {   
                  sftp.disconnect();   
                 // log.info("sftp is closed already");   
              }   
          }   
          if (sshSession != null) {   
              if (sshSession.isConnected()) {   
                sshSession.disconnect();   
                // log.info("sshSession is closed already");
              }   
          }   
      }   
      public static void main(String[] args) throws IOException{
      SftpTools s = new SftpTools();
        String host= "";
        //String host= "";
        int port= 22;
        String username= "";
        //String username= "";
        String password= "";
        //String password= "";
        ChannelSftp connect = s.connect(host, port, username, password);
        String directory = "/opt/";
        //String fileName = "test3.txt";
        //s.mkdir(directory, fileName, connect);
//        Vector listFiles;
//        try {
//          listFiles = s.listFiles(directory, connect);
//          for (int i = 0; i < listFiles.size(); i++) {
//            /*log.info(listFiles.get(i));*/
//          	System.out.println(listFiles.get(i));
//          }
//        } catch (SftpException e) {
//          // TODO Auto-generated catch block
//          e.printStackTrace();
//        }
        InputStream input = s.download(directory, "D_20200902.txt", connect);
        File tempFile = new File("F:\\test");
        if (!tempFile.exists()) {
        tempFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(tempFile.getPath() + File.separator + "D_20200902.txt");
        byte[] b = new byte[2048];
        int len;
        while ((len = input.read(b)) != -1) {
        out.write(b, 0, len);
        }
        System.out.println("文件下载成功");
        s.logout(connect);
    }
}

以上代码导入后,需要加入一个jsch的jar包

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>

快去试试吧

posted on 2021-03-05 11:23  海哥哥99  阅读(828)  评论(0编辑  收藏  举报

导航