欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java使用Sftp和Ftp实现对文件的上传和下载

程序员文章站 2022-07-06 09:18:44
sftp和ftp两种方式区别,还不清楚的,请自行百度查询,此处不多赘述。完整代码地址在结尾!!第一步,导入maven依赖...

sftp和ftp两种方式区别,还不清楚的,请自行百度查询,此处不多赘述。完整代码地址在结尾!!

第一步,导入maven依赖

<!-- ftp依赖包 -->
<dependency>
  <groupid>commons-net</groupid>
  <artifactid>commons-net</artifactid>
  <version>3.6</version>
</dependency>
<!-- sftp依赖包 -->
<dependency>
  <groupid>com.jcraft</groupid>
  <artifactid>jsch</artifactid>
  <version>0.1.55</version>
</dependency>
<dependency>
  <groupid>commons-io</groupid>
  <artifactid>commons-io</artifactid>
  <version>2.6</version>
</dependency>

第二步,创建并编写sftputils类,运行main方法查看效果,如下

import com.jcraft.jsch.*;
import lombok.extern.slf4j.slf4j;
import org.apache.commons.io.ioutils;

import java.io.file;
import java.io.fileinputstream;
import java.io.fileoutputstream;
import java.io.inputstream;
import java.util.properties;
import java.util.vector;

/**
 * @description: sftp上传下载工具类
 * @author: jinhaoxun
 * @date: 2020/1/16 16:13
 * @version: 1.0.0
 */
@slf4j
public class sftputils {

  public static void main(string[] args) throws exception {
    log.info("测试开始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    // 1
    file file = new file("e:\\2.xlsx");
    inputstream inputstream = new fileinputstream(file);
    sftputils.uploadfile("", "", "", 22, "/usr/local",
        "/testfile/", "test.xlsx", null, inputstream);

    // 2
    sftputils.downloadfile("", "", "", 22,null,
        "/usr/local/testfile/", "test.csv","/users/ao/desktop/test.csv");

    // 3
    sftputils.deletefile("", "", "", 22,null,
        "/usr/local/testfile/", "test.xlsx");

    // 4
    vector<?> filelist = sftputils.getfilelist("", "", "",
        22, null,"/usr/local/testfile/");
    log.info(filelist.tostring());
    log.info("测试结束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
  }

  /**
   * @author: jinhaoxun
   * @description: 下载文件
   * @param username 用户名
   * @param password 密码
   * @param host ip
   * @param port 端口
   * @param basepath 根路径
   * @param filepath 文件路径(加上根路径)
   * @param filename 文件名
   * @param privatekey 秘钥
   * @param input 文件流
   * @date: 2020/1/16 21:23
   * @return: void
   * @throws: exception
   */
  public static void uploadfile(string username, string password, string host, int port, string basepath,
                   string filepath, string filename, string privatekey, inputstream input) throws exception {

    session session = null;
    channelsftp sftp = null;
    // 连接sftp服务器
    try {
      jsch jsch = new jsch();
      if (privatekey != null) {
        // 设置私钥
        jsch.addidentity(privatekey);
      }

      session = jsch.getsession(username, host, port);

      if (password != null) {
        session.setpassword(password);
      }
      properties config = new properties();
      config.put("stricthostkeychecking", "no");

      session.setconfig(config);
      session.connect();

      channel channel = session.openchannel("sftp");
      channel.connect();

      sftp = (channelsftp) channel;
    } catch (jschexception e) {
      e.printstacktrace();
    }
    // 将输入流的数据上传到sftp作为文件
    try {
      sftp.cd(basepath);
      sftp.cd(filepath);
    } catch (sftpexception e) {
      //目录不存在,则创建文件夹
      string [] dirs=filepath.split("/");
      string temppath=basepath;
      for(string dir:dirs){
        if(null== dir || "".equals(dir)){
          continue;
        }
        temppath+="/"+dir;
        try{
          sftp.cd(temppath);
        }catch(sftpexception ex){
          sftp.mkdir(temppath);
          sftp.cd(temppath);
        }
      }
    }
    //上传文件
    sftp.put(input, filename);
    //关闭连接 server
    if (sftp != null) {
      if (sftp.isconnected()) {
        sftp.disconnect();
      }
    }
    //关闭连接 server
    if (session != null) {
      if (session.isconnected()) {
        session.disconnect();
      }
    }
  }

  /**
   * @author: jinhaoxun
   * @description: 下载文件
   * @param username 用户名
   * @param password 密码
   * @param host ip
   * @param port 端口
   * @param privatekey 秘钥
   * @param directory 文件路径
   * @param downloadfile 文件名
   * @param savefile 存在本地的路径
   * @date: 2020/1/16 21:22
   * @return: void
   * @throws: exception
   */
  public static void downloadfile(string username, string password, string host, int port, string privatekey, string directory,
                string downloadfile, string savefile) throws exception{
    session session = null;
    channelsftp sftp = null;
    // 连接sftp服务器
    try {
      jsch jsch = new jsch();
      if (privatekey != null) {
        // 设置私钥
        jsch.addidentity(privatekey);
      }

      session = jsch.getsession(username, host, port);

      if (password != null) {
        session.setpassword(password);
      }
      properties config = new properties();
      config.put("stricthostkeychecking", "no");

      session.setconfig(config);
      session.connect();

      channel channel = session.openchannel("sftp");
      channel.connect();

      sftp = (channelsftp) channel;
    } catch (jschexception e) {
      e.printstacktrace();
    }
    if (directory != null && !"".equals(directory)) {
      sftp.cd(directory);
    }
    file file = new file(savefile);
    sftp.get(downloadfile, new fileoutputstream(file));
  }

  /**
   * @author: jinhaoxun
   * @description: 下载文件
   * @param username 用户名
   * @param password 密码
   * @param host ip
   * @param port 端口
   * @param privatekey 秘钥
   * @param directory 文件路径
   * @param downloadfile 文件名
   * @date: 2020/1/16 21:21
   * @return: byte[]
   * @throws: exception
   */
  public static byte[] downloadfile(string username, string password, string host, int port, string privatekey,
                 string directory, string downloadfile) throws exception{
    session session = null;
    channelsftp sftp = null;
    // 连接sftp服务器
    try {
      jsch jsch = new jsch();
      if (privatekey != null) {
        // 设置私钥
        jsch.addidentity(privatekey);
      }

      session = jsch.getsession(username, host, port);

      if (password != null) {
        session.setpassword(password);
      }
      properties config = new properties();
      config.put("stricthostkeychecking", "no");

      session.setconfig(config);
      session.connect();

      channel channel = session.openchannel("sftp");
      channel.connect();

      sftp = (channelsftp) channel;
    } catch (jschexception e) {
      e.printstacktrace();
    }
    if (directory != null && !"".equals(directory)) {
      sftp.cd(directory);
    }
    inputstream is = sftp.get(downloadfile);
    byte[] filedata = ioutils.tobytearray(is);
    return filedata;
  }

  /**
   * @author: jinhaoxun
   * @description: 删除文件
   * @param username 用户名
   * @param password 密码
   * @param host ip
   * @param port 端口
   * @param privatekey 秘钥
   * @param directory 文件路径
   * @param deletefile 文件名
   * @date: 2020/1/16 21:24
   * @return: void
   * @throws: exception
   */
  public static void deletefile(string username, string password, string host, int port, string privatekey,
               string directory, string deletefile) throws exception{
    session session = null;
    channelsftp sftp = null;
    // 连接sftp服务器
    try {
      jsch jsch = new jsch();
      if (privatekey != null) {
        // 设置私钥
        jsch.addidentity(privatekey);
      }

      session = jsch.getsession(username, host, port);

      if (password != null) {
        session.setpassword(password);
      }
      properties config = new properties();
      config.put("stricthostkeychecking", "no");

      session.setconfig(config);
      session.connect();

      channel channel = session.openchannel("sftp");
      channel.connect();

      sftp = (channelsftp) channel;
    } catch (jschexception e) {
      e.printstacktrace();
    }
    sftp.cd(directory);
    sftp.rm(deletefile);
  }

  /**
   * @author: jinhaoxun
   * @description: 列出目录下的文件
   * @param username 用户名
   * @param password 密码
   * @param host ip
   * @param port 端口
   * @param privatekey 秘钥
   * @param directory 要列出的目录
   * @date: 2020/1/16 21:25
   * @return: java.util.vector<?>
   * @throws: exception
   */
  public static vector<?> getfilelist(string username, string password, string host, int port, string privatekey,
                   string directory) throws exception {
    session session = null;
    channelsftp sftp = null;
    // 连接sftp服务器
    try {
      jsch jsch = new jsch();
      if (privatekey != null) {
        // 设置私钥
        jsch.addidentity(privatekey);
      }

      session = jsch.getsession(username, host, port);

      if (password != null) {
        session.setpassword(password);
      }
      properties config = new properties();
      config.put("stricthostkeychecking", "no");

      session.setconfig(config);
      session.connect();

      channel channel = session.openchannel("sftp");
      channel.connect();

      sftp = (channelsftp) channel;
    } catch (jschexception e) {
      e.printstacktrace();
    }
    return sftp.ls(directory);
  }

}

第三步,创建并编写ftputils类,运行main方法查看效果,如下

import lombok.extern.slf4j.slf4j;
import org.apache.commons.net.ftp.ftp;
import org.apache.commons.net.ftp.ftpclient;
import org.apache.commons.net.ftp.ftpfile;
import org.apache.commons.net.ftp.ftpreply;

import java.io.*;

/**
 * @description: ftp上传下载工具类
 * @author: jinhaoxun
 * @date: 2020/1/16 15:46
 * @version: 1.0.0
 */
@slf4j
public class ftputils {

  public static void main(string[] args) throws exception {
    log.info("测试开始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    // 1
    file file = new file("e:\\2.xlsx");
    inputstream inputstream = new fileinputstream(file);
    ftputils.uploadfile("", 21, "", "", "/usr/local",
        "/testfile/", "test.xlsx", inputstream);

    // 2
    ftputils.downloadfile("", 21, "", "","/usr/local/testfile/",
        "test.csv", "/users/ao/desktop/test.csv");
    log.info("测试结束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
  }

  /**
   * @author: jinhaoxun
   * @description: 向ftp服务器上传文件
   * @param host ftp服务器hostname
   * @param port ftp服务器端口
   * @param username ftp登录账号
   * @param password ftp登录密码
   * @param basepath ftp服务器基础目录
   * @param filepath ftp服务器文件存放路径。例如分日期存放:/2015/01/01。文件的路径为basepath+filepath
   * @param filename 上传到ftp服务器上的文件名
   * @param input 本地要上传的文件的 输入流
   * @date: 2020/1/16 19:31
   * @return: boolean
   * @throws: exception
   */
  public static boolean uploadfile(string host, int port, string username, string password, string basepath,
                   string filepath, string filename, inputstream input) throws exception{
    boolean result = false;
    ftpclient ftp = new ftpclient();
    try {
      int reply;
      // 连接ftp服务器
      ftp.connect(host, port);
      // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接ftp服务器
      // 登录
      ftp.login(username, password);
      reply = ftp.getreplycode();
      if (!ftpreply.ispositivecompletion(reply)) {
        ftp.disconnect();
        return result;
      }
      //切换到上传目录
      if (!ftp.changeworkingdirectory(basepath+filepath)) {
        //如果目录不存在创建目录
        string[] dirs = filepath.split("/");
        string temppath = basepath;
        for (string dir : dirs) {
          if (null == dir || "".equals(dir)){
            continue;
          }
          temppath += "/" + dir;
          if (!ftp.changeworkingdirectory(temppath)) {
            if (!ftp.makedirectory(temppath)) {
              return result;
            } else {
              ftp.changeworkingdirectory(temppath);
            }
          }
        }
      }
      //设置上传文件的类型为二进制类型
      ftp.setfiletype(ftp.binary_file_type);
      //上传文件
      if (!ftp.storefile(filename, input)) {
        return result;
      }
      input.close();
      ftp.logout();
      result = true;
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      if (ftp.isconnected()) {
        try {
          ftp.disconnect();
        } catch (ioexception ioe) {
        }
      }
    }
    return result;
  }

  /**
   * @author: jinhaoxun
   * @description: 从ftp服务器下载文件
   * @param host ftp服务器hostname
   * @param port ftp服务器端口
   * @param username ftp登录账号
   * @param password ftp登录密码
   * @param remotepath ftp服务器上的相对路径
   * @param filename 要下载的文件名
   * @param localpath 下载后保存到本地的路径
   * @date: 2020/1/16 19:34
   * @return: boolean
   * @throws: exception
   */
  public static boolean downloadfile(string host, int port, string username, string password, string remotepath,
                    string filename, string localpath) throws exception {

    boolean result = false;
    ftpclient ftp = new ftpclient();
    try {
      int reply;
      ftp.connect(host, port);
      // 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接ftp服务器
      // 登录
      ftp.login(username, password);
      reply = ftp.getreplycode();
      if (!ftpreply.ispositivecompletion(reply)) {
        ftp.disconnect();
        return result;
      }
      // 转移到ftp服务器目录
      ftp.changeworkingdirectory(remotepath);
      ftpfile[] fs = ftp.listfiles();
      for (ftpfile ff : fs) {
        if (ff.getname().equals(filename)) {
          java.io.file localfile = new file(localpath + "/" + ff.getname());

          outputstream is = new fileoutputstream(localfile);
          ftp.retrievefile(ff.getname(), is);
          is.close();
        }
      }
      ftp.logout();
      result = true;
    } catch (ioexception e) {
      e.printstacktrace();
    } finally {
      if (ftp.isconnected()) {
        try {
          ftp.disconnect();
        } catch (ioexception ioe) {
        }
      }
    }
    return result;
  }  
}

完整代码地址:
注:此工程包含多个包,ftputils代码均在com.luoyu.java.ftp包下
注:此工程包含多个包,sftputils代码均在com.luoyu.java.sftp包下

到此这篇关于java使用sftp和ftp实现对文件的上传和下载的文章就介绍到这了,更多相关java使用sftp和ftp文件上传和下载内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!