最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java使用Sftp和Ftp實(shí)現(xiàn)對(duì)文件的上傳和下載

 更新時(shí)間:2021年03月25日 11:59:24   作者:天不生我落雨  
這篇文章主要介紹了Java使用Sftp和Ftp實(shí)現(xiàn)對(duì)文件的上傳和下載,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

sftp和ftp兩種方式區(qū)別,還不清楚的,請(qǐng)自行百度查詢(xún),此處不多贅述。完整代碼地址在結(jié)尾?。?br />

第一步,導(dǎo)入maven依賴(lài)

<!-- FTP依賴(lài)包 -->
<dependency>
  <groupId>commons-net</groupId>
  <artifactId>commons-net</artifactId>
  <version>3.6</version>
</dependency>
<!-- SFTP依賴(lài)包 -->
<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>

第二步,創(chuàng)建并編寫(xiě)SftpUtils類(lèi),運(yùn)行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上傳下載工具類(lèi)
 * @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("測(cè)試開(kāi)始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    // 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("測(cè)試結(jié)束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
  }

  /**
   * @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服務(wù)器
    try {
      JSch jsch = new JSch();
      if (privateKey != null) {
        // 設(shè)置私鑰
        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();
    }
    // 將輸入流的數(shù)據(jù)上傳到sftp作為文件
    try {
      sftp.cd(basePath);
      sftp.cd(filePath);
    } catch (SftpException e) {
      //目錄不存在,則創(chuàng)建文件夾
      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);
    //關(guān)閉連接 server
    if (sftp != null) {
      if (sftp.isConnected()) {
        sftp.disconnect();
      }
    }
    //關(guān)閉連接 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服務(wù)器
    try {
      JSch jsch = new JSch();
      if (privateKey != null) {
        // 設(shè)置私鑰
        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服務(wù)器
    try {
      JSch jsch = new JSch();
      if (privateKey != null) {
        // 設(shè)置私鑰
        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服務(wù)器
    try {
      JSch jsch = new JSch();
      if (privateKey != null) {
        // 設(shè)置私鑰
        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服務(wù)器
    try {
      JSch jsch = new JSch();
      if (privateKey != null) {
        // 設(shè)置私鑰
        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);
  }

}

第三步,創(chuàng)建并編寫(xiě)FtpUtils類(lèi),運(yùn)行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上傳下載工具類(lèi)
 * @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("測(cè)試開(kāi)始!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
    // 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("測(cè)試結(jié)束!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
  }

  /**
   * @Author: jinhaoxun
   * @Description: 向FTP服務(wù)器上傳文件
   * @param host FTP服務(wù)器hostname
   * @param port FTP服務(wù)器端口
   * @param userName FTP登錄賬號(hào)
   * @param password FTP登錄密碼
   * @param basePath FTP服務(wù)器基礎(chǔ)目錄
   * @param filePath FTP服務(wù)器文件存放路徑。例如分日期存放:/2015/01/01。文件的路徑為basePath+filePath
   * @param filename 上傳到FTP服務(wù)器上的文件名
   * @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服務(wù)器
      ftp.connect(host, port);
      // 如果采用默認(rèn)端口,可以使用ftp.connect(host)的方式直接連接FTP服務(wù)器
      // 登錄
      ftp.login(userName, password);
      reply = ftp.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        return result;
      }
      //切換到上傳目錄
      if (!ftp.changeWorkingDirectory(basePath+filePath)) {
        //如果目錄不存在創(chuàng)建目錄
        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);
            }
          }
        }
      }
      //設(shè)置上傳文件的類(lèi)型為二進(jìn)制類(lèi)型
      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服務(wù)器下載文件
   * @param host FTP服務(wù)器hostname
   * @param port FTP服務(wù)器端口
   * @param userName FTP登錄賬號(hào)
   * @param password FTP登錄密碼
   * @param remotePath FTP服務(wù)器上的相對(duì)路徑
   * @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);
      // 如果采用默認(rèn)端口,可以使用ftp.connect(host)的方式直接連接FTP服務(wù)器
      // 登錄
      ftp.login(userName, password);
      reply = ftp.getReplyCode();
      if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        return result;
      }
      // 轉(zhuǎn)移到FTP服務(wù)器目錄
      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;
  }  
}

完整代碼地址:https://github.com/luoyusoft/java-demo
注:此工程包含多個(gè)包,F(xiàn)tpUtils代碼均在com.luoyu.java.ftp包下
注:此工程包含多個(gè)包,SftpUtils代碼均在com.luoyu.java.sftp包下

到此這篇關(guān)于Java使用Sftp和Ftp實(shí)現(xiàn)對(duì)文件的上傳和下載的文章就介紹到這了,更多相關(guān)Java使用Sftp和Ftp文件上傳和下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家! 

相關(guān)文章

  • JVM:晚期(運(yùn)行期)優(yōu)化的深入理解

    JVM:晚期(運(yùn)行期)優(yōu)化的深入理解

    今天小編就為大家分享一篇關(guān)于JVM:晚期(運(yùn)行期)優(yōu)化的深入理解,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-02-02
  • 基于java中兩個(gè)對(duì)象屬性的比較

    基于java中兩個(gè)對(duì)象屬性的比較

    下面小編就為大家?guī)?lái)一篇基于java中兩個(gè)對(duì)象屬性的比較。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-09-09
  • 基于Pinpoint對(duì)SpringCloud微服務(wù)項(xiàng)目實(shí)現(xiàn)全鏈路監(jiān)控的問(wèn)題

    基于Pinpoint對(duì)SpringCloud微服務(wù)項(xiàng)目實(shí)現(xiàn)全鏈路監(jiān)控的問(wèn)題

    這篇文章主要介紹了基于Pinpoint對(duì)SpringCloud微服務(wù)項(xiàng)目實(shí)現(xiàn)全鏈路監(jiān)控的問(wèn)題,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-02-02
  • spring之SpEL表達(dá)式詳解

    spring之SpEL表達(dá)式詳解

    這篇文章主要介紹了spring之SpEL表達(dá)式詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • SpringBoot整合TomCat實(shí)現(xiàn)本地圖片服務(wù)器代碼解析

    SpringBoot整合TomCat實(shí)現(xiàn)本地圖片服務(wù)器代碼解析

    這篇文章主要介紹了SpringBoot整合TomCat實(shí)現(xiàn)本地圖片服務(wù)器代碼解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-08-08
  • 詳解Java中Math.round()的取整規(guī)則

    詳解Java中Math.round()的取整規(guī)則

    這篇文章主要介紹了詳解Java中Math.round()的取整規(guī)則,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • Java Web十條開(kāi)發(fā)實(shí)用小知識(shí)

    Java Web十條開(kāi)發(fā)實(shí)用小知識(shí)

    這篇文章主要介紹了Java Web十條開(kāi)發(fā)實(shí)用小知識(shí)的相關(guān)資料,需要的朋友可以參考下
    2016-05-05
  • Java中l(wèi)ambda表達(dá)式實(shí)現(xiàn)aop切面功能

    Java中l(wèi)ambda表達(dá)式實(shí)現(xiàn)aop切面功能

    本文主要介紹了Java中l(wèi)ambda表達(dá)式實(shí)現(xiàn)aop切面功能,文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2022-02-02
  • Java jvm中Code Cache案例詳解

    Java jvm中Code Cache案例詳解

    這篇文章主要介紹了Java jvm中Code Cache案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • Mybatis Log Plugin的使用方式

    Mybatis Log Plugin的使用方式

    這篇文章主要介紹了Mybatis Log Plugin的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-02-02

最新評(píng)論

原阳县| 盐边县| 马公市| 万州区| 临澧县| 青神县| 平塘县| 聂荣县| 察哈| 娱乐| 鄯善县| 永寿县| 山东省| 资中县| 堆龙德庆县| 临沂市| 外汇| 大冶市| 临泽县| 阜南县| 沾益县| 潼南县| 靖边县| 宝兴县| 铜梁县| 澜沧| 蒲江县| 高陵县| 梅河口市| 墨竹工卡县| 通化市| 资源县| 靖宇县| 桐城市| 香河县| 修文县| 亚东县| 甘肃省| 溧阳市| 穆棱市| 宁明县|