iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >Java如何使用Sftp和Ftp实现对文件的上传和下载
  • 566
分享到

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

2023-06-14 08:06:30 566人浏览 泡泡鱼
摘要

这篇文章将为大家详细讲解有关Java如何使用Sftp和Ftp实现对文件的上传和下载,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。第一步,导入Maven依赖<!-- FTP依赖包 

这篇文章将为大家详细讲解有关Java如何使用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;@Slf4jpublic 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("测试结束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");  }    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();      }    }  }    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));  }    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;  }    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);  }    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.*;@Slf4jpublic 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("测试结束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");  }    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;  }    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;  }  }

关于“Java如何使用Sftp和Ftp实现对文件的上传和下载”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

--结束END--

本文标题: Java如何使用Sftp和Ftp实现对文件的上传和下载

本文链接: https://www.lsjlt.com/news/269138.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Java如何使用Sftp和Ftp实现对文件的上传和下载
    这篇文章将为大家详细讲解有关Java如何使用Sftp和Ftp实现对文件的上传和下载,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。第一步,导入maven依赖<!-- FTP依赖包 ...
    99+
    2023-06-14
  • Java使用Sftp和Ftp实现对文件的上传和下载
    sftp和ftp两种方式区别,还不清楚的,请自行百度查询,此处不多赘述。完整代码地址在结尾!! 第一步,导入maven依赖 <!-- FTP依赖包 --> <...
    99+
    2024-04-02
  • Python如何使用sftp实现上传和下载功能
    这篇文章主要介绍了Python如何使用sftp实现上传和下载功能,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。python可以做什么Python是一种编程语言,内置了许多有效...
    99+
    2023-06-14
  • Python使用sftp实现上传和下载功能
    在Python中可以使用paramiko模块中的sftp登陆远程主机,实现上传和下载功能。 1.功能实现 1、根据输入参数判断是文件还是目录,进行上传和下载 2、本地参数local需...
    99+
    2024-04-02
  • java实现文件上传和下载
    本文实例为大家分享了java实现文件上传和下载的具体代码,供大家参考,具体内容如下 文件的上传 upload:文件上传 客户端通过表单的文件域file  把客户端的文件 上...
    99+
    2024-04-02
  • 使用hutool进行ftp文件下载和上传
    1 引入依赖 cn.hutool hutool-all 5.8.15 commons-net commons-net 3.6 2 工具类 package ftp;...
    99+
    2023-10-20
    java
  • java实现ftp文件上传下载功能
    本文实例为大家分享了ftp实现文件上传下载的具体代码,供大家参考,具体内容如下package getUrlPic;import java.io.ByteArrayInputStream;import java.io.IOException;...
    99+
    2023-05-31
    ftp 上传 下载
  • Linux中怎么使用sFTP进行上传和下载文件
    这篇文章主要讲解了“Linux中怎么使用sFTP进行上传和下载文件”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“Linux中怎么使用sFTP进行上传和下载文件”吧!sftp是一种安全的文件传...
    99+
    2023-06-27
  • SpringBoot如何实现上传和下载文件
    这篇文章主要介绍SpringBoot如何实现上传和下载文件,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!技术概述我们的项目是实现一个论坛。在论坛上发布博客时应该要可以上传文件,用户阅读博客是应该要可以下载文件。于是我...
    99+
    2023-06-20
  • php如何实现文件的上传和下载
    这篇文章将为大家详细讲解有关php如何实现文件的上传和下载,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。php有什么用php是一个嵌套的缩写名称,是英文超级文本预处理语言,它的语法混合了C、Java、Pe...
    99+
    2023-06-14
  • Java实现ftp的上传、下载
    ftp登录命令: windows环境下登录:文件管理资源的地址栏中输入“ftp://ip:port”,然后根据提示输入账号、密码。linux环境下登录:ftp ip,然后根据提示输入账号、密码,lin...
    99+
    2023-09-26
    java linux 服务器
  • Go实现文件上传和下载
    本文实例为大家分享了Go实现文件上传和下载的具体代码,供大家参考,具体内容如下 一.文件上传 文件上传:客户端把上传文件转换为二进制流后发送给服务器,服务器对二进制流进行解析 HTM...
    99+
    2024-04-02
  • vue实现文件上传和下载
    本文实例为大家分享了vue实现文件上传和下载的具体代码,供大家参考,具体内容如下 文件上传 vue中的文件上传主要分为两步:前台获取到文件和提交到后台 获取文件 前台获取文件,主要是...
    99+
    2024-04-02
  • springMVC实现文件上传和下载
    本文实例为大家分享了springMVC实现文件上传和下载的具体代码,供大家参考,具体内容如下 1准备工作 web.xml文件导入DispatcherServlet,Character...
    99+
    2024-04-02
  • ASP.NETCore实现文件上传和下载
    本文实例为大家分享了ASP.NET Core实现文件上传和下载的具体代码,供大家参考,具体内容如下 一、文件上传 1.1 获取文件后缀 /// <summary> ///...
    99+
    2024-04-02
  • Java如何实现FTP文件上传
    这篇文章给大家分享的是有关Java如何实现FTP文件上传的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。一、配置FTP文件服务器以Ubuntu为例FTP两种模式简介PORT(主动模式)第一步FTP客户端首先随机选择...
    99+
    2023-06-15
  • Python使用sftp实现传文件夹和文件
    利用python的sftp实现文件上传,可以是文件,也可以是文件夹。 版本Python2.7.13 应该不用pip安装更多的插件,都是自带的 不多说 上代码 # -*- codi...
    99+
    2024-04-02
  • SpringBoot如何集成SFTP客户端实现文件上传下载
    这篇文章主要介绍“SpringBoot如何集成SFTP客户端实现文件上传下载”,在日常操作中,相信很多人在SpringBoot如何集成SFTP客户端实现文件上传下载问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答...
    99+
    2023-07-06
  • 利用java如何实现上传ftp文件
    今天就跟大家聊聊有关利用java如何实现上传ftp文件,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。准备条件:java实现ftp上传用到了commons-net-3.3.jar包首先...
    99+
    2023-05-31
    java ftp上传 ava
  • Spring MVC实现文件上传和下载
    本文实例为大家分享了Spring MVC实现文件上传和下载的具体代码,供大家参考,具体内容如下 文件上传 1、导入主要依赖 <!--文件上传--> <depe...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作