Java8实现FTP及SFTP文件上传下载

来自:互联网
时间:2020-09-19
阅读:

有网上的代码,也有自己的理解,代码备份

  一般连接Windows服务器使用FTP,连接linux服务器使用SFTP。linux都是通过SFTP上传文件,不需要额外安装,非要使用FTP的话,还得安装FTP服务(虽然刚开始我就是这么干的)。

  另外就是jdk1.8和jdk1.7之前的方法有些不同,网上有很多jdk1.7之前的介绍,本篇是jdk1.8的

添加依赖Jsch-0.1.54.jar

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

FTP上传下载文件例子

import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpProtocolException;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * Java自带的API对FTP的操作
 */
public class Test {
  private FtpClient ftpClient;

  Test(){
     /*
    使用默认的端口号、用户名、密码以及根目录连接FTP服务器
     */
    this.connectServer("192.168.56.130", 21, "jiashubing", "123456", "/home/jiashubing/ftp/anonymous/");
  }

  public void connectServer(String ip, int port, String user, String password, String path) {
    try {
      /* ******连接服务器的两种方法*******/
      ftpClient = FtpClient.create();
      try {
        SocketAddress addr = new InetSocketAddress(ip, port);
        ftpClient.connect(addr);
        ftpClient.login(user, password.toCharArray());
        System.out.println("login success!");
        if (path.length() != 0) {
          //把远程系统上的目录切换到参数path所指定的目录
          ftpClient.changeDirectory(path);
        }
      } catch (FtpProtocolException e) {
        e.printStackTrace();
      }
    } catch (IOException ex) {
      ex.printStackTrace();
      throw new RuntimeException(ex);
    }
  }

  /**
   * 关闭连接
   */
  public void closeConnect() {
    try {
      ftpClient.close();
      System.out.println("disconnect success");
    } catch (IOException ex) {
      System.out.println("not disconnect");
      ex.printStackTrace();
      throw new RuntimeException(ex);
    }
  }

  /**
   * 上传文件
   * @param localFile 本地文件
   * @param remoteFile 远程文件
   */
  public void upload(String localFile, String remoteFile) {
    File file_in = new File(localFile);
    try(OutputStream os = ftpClient.putFileStream(remoteFile);
      FileInputStream is = new FileInputStream(file_in)) {
      byte[] bytes = new byte[1024];
      int c;
      while ((c = is.read(bytes)) != -1) {
        os.write(bytes, 0, c);
      }
      System.out.println("upload success");
    } catch (IOException ex) {
      System.out.println("not upload");
      ex.printStackTrace();
    } catch (FtpProtocolException e) {
      e.printStackTrace();
    }
  }

  /**
   * 下载文件。获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
   * @param remoteFile 远程文件路径(服务器端)
   * @param localFile 本地文件路径(客户端)
   */
  public void download(String remoteFile, String localFile) {
    File file_in = new File(localFile);
    try(InputStream is = ftpClient.getFileStream(remoteFile);
      FileOutputStream os = new FileOutputStream(file_in)){

      byte[] bytes = new byte[1024];
      int c;
      while ((c = is.read(bytes)) != -1) {
        os.write(bytes, 0, c);
      }
      System.out.println("download success");
    } catch (IOException ex) {
      System.out.println("not download");
      ex.printStackTrace();
    }catch (FtpProtocolException e) {
      e.printStackTrace();
    }
  }

  public static void mAIn(String agrs[]) {
    Test fu = new Test();

    //下载测试
    String filepath[] = {"aa.xlsx","bb.xlsx"};
    String localfilepath[] = {"E:/lalala/aa.xlsx","E:/lalala/bb.xlsx"};
    for (int i = 0; i < filepath.length; i++) {
      fu.download(filepath[i], localfilepath[i]);
    }
    //上传测试
    String localfile = "E:/lalala/tt.xlsx";
    String remotefile = "tt.xlsx";        //上传
    fu.upload(localfile, remotefile);
    fu.closeConnect();
  }
}

SFTP上传下载文件例子

import com.jcraft.jsch.*;

import java.util.Properties;

/**
 * 解释一下SFTP的整个调用过程,这个过程就是通过Ip、Port、Username、Password获取一个Session,
 * 然后通过Session打开SFTP通道(获得SFTP Channel对象),再在建立通道(Channel)连接,最后我们就是
 * 通过这个Channel对象来调用SFTP的各种操作方法.总是要记得,我们操作完SFTP需要手动断开Channel连接与Session连接。
 * @author jiashubing
 * @since 2018/5/8
 */
public class SftpCustom {

  private ChannelSftp channel;
  private Session session;
  private String sftpPath;

  SftpCustom() {
     /*
     使用端口号、用户名、密码以连接SFTP服务器
     */
    this.connectServer("192.168.56.130", 22, "jiashubing", "123456", "/home/ftp/");
  }

  SftpCustom(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String sftpPath) {
    this.connectServer(ftpHost, ftpPort, ftpUserName, ftpPassword, sftpPath);
  }

  public void connectServer(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String sftpPath) {
    try {
      this.sftpPath = sftpPath;

      // 创建JSch对象
      JSch jsch = new JSch();
      // 根据用户名,主机ip,端口获取一个Session对象
      session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
      if (ftpPassword != null) {
        // 设置密码
        session.setPassword(ftpPassword);
      }
      Properties configTemp = new Properties();
      configTemp.put("StrictHostKeyChecking", "no");
      // 为Session对象设置properties
      session.setConfig(configTemp);
      // 设置timeout时间
      session.setTimeout(60000);
      session.connect();
      // 通过Session建立链接
      // 打开SFTP通道
      channel = (ChannelSftp) session.openChannel("sftp");
      // 建立SFTP通道的连接
      channel.connect();
    } catch (JSchException e) {
      //throw new RuntimeException(e);
    }
  }

  /**
   * 断开SFTP Channel、Session连接
   */
  public void closeChannel() {
    try {
      if (channel != null) {
        channel.disconnect();
      }
      if (session != null) {
        session.disconnect();
      }
    } catch (Exception e) {
      //
    }
  }

  /**
   * 上传文件
   *
   * @param localFile 本地文件
   * @param remoteFile 远程文件
   */
  public void upload(String localFile, String remoteFile) {
    try {
      remoteFile = sftpPath + remoteFile;
      channel.put(localFile, remoteFile, ChannelSftp.OVERWRITE);
      channel.quit();
    } catch (SftpException e) {
      //e.printStackTrace();
    }
  }

  /**
   * 下载文件
   *
   * @param remoteFile 远程文件
   * @param localFile 本地文件
   */
  public void download(String remoteFile, String localFile) {
    try {
      remoteFile = sftpPath + remoteFile;
      channel.get(remoteFile, localFile);
      channel.quit();
    } catch (SftpException e) {
      //e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    SftpCustom sftpCustom = new SftpCustom();
    //上传测试
    String localfile = "E:/lalala/tt.xlsx";
    String remotefile = "/home/ftp/tt2.xlsx";
    sftpCustom.upload(localfile, remotefile);
    //下载测试
    sftpCustom.download(remotefile, "E:/lalala/tt3.xlsx");
    sftpCustom.closeChannel();
  }
}

Jsch-0.1.54.jar 学习了解

ChannelSftp类是JSch实现SFTP核心类,它包含了所有SFTP的方法,如:

  文件上传put(),
  文件下载get(),
  进入指定目录cd().
  得到指定目录下的文件列表ls().
  重命名指定文件或目录rename().
  删除指定文件rm(),创建目录mkdir(),删除目录rmdir().

大家引用方法时可以快速参考一下,具体传参需参考源码~

最后还要提一下的就是JSch支持的三种文件传输模式:

  ● APPEND 追加模式,如果目标文件已存在,传输的文件将在目标文件后追加。

  ● RESUME 恢复模式,如果文件已经传输一部分,这时由于网络或其他任何原因导致文件传输中断,如果下一次传输相同的文件,则会从上一次中断的地方续传。

  ● OVERWRITE 完全覆盖模式,这是JSch的默认文件传输模式,即如果目标文件已经存在,传输的文件将完全覆盖目标文件,产生新的文件。

FTP和SFTP区别

  FTP是一种文件传输协议,一般是为了方便数据共享的。包括一个FTP服务器和多个FTP客户端。FTP客户端通过FTP协议在服务器上下载资源。而SFTP协议是在FTP的基础上对数据进行加密,使得传输的数据相对来说更安全。但是这种安全是以牺牲效率为代价的,也就是说SFTP的传输效率比FTP要低(不过现实使用当中,没有发现多大差别)。个人肤浅的认为就是:一;FTP要安装,SFTP不要安装。二;SFTP更安全,但更安全带来副作用就是的效率比FTP要低些。

建议使用sftp代替ftp。

主要因为:

  1、可以不用额外安装任何服务器端程序

  2、会更省系统资源。

  3、SFTP使用加密传输认证信息和传输数据,相对来说会更安全。

  4、也不需要单独配置,对新手来说比较简单(开启SSH默认就开启了SFTP)。

返回顶部
顶部