首页 > 其他分享 >ftp与sftp工具类

ftp与sftp工具类

时间:2023-08-04 15:34:26浏览次数:35  
标签:ftp String param sftp try static catch 工具 ftpClient

1、ftp、ftps、sftp的区别

https://www.cnblogs.com/Javi/p/6904587.html

2、ftp

package com.zhhs.common.utils.ftp;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.tomcat.util.http.fileupload.FileItem;

import java.io.*;

/**
 * FTP工具类
 * 文件上传
 * 文件下载
 */
@Slf4j
public class FtpUtil {

    /**
     * 设置缓冲区大小4M
     **/
    private static final int BUFFER_SIZE = 1024 * 1024 * 4;

    /**
     * 本地字符编码
     **/
    private static String LOCAL_CHARSET = "GBK";

    /**
     * UTF-8字符编码
     **/
    private static final String CHARSET_UTF8 = "UTF-8";

    /**
     * OPTS UTF8字符串常量
     **/
    private static final String OPTS_UTF8 = "OPTS UTF8";

    /**
     * FTP协议里面,规定文件名编码为iso-8859-1
     **/
    private static final String SERVER_CHARSET = "ISO-8859-1";

    /**
     * 连接FTP服务器
     */
    private static FTPClient login(String host, Integer port, String username, String password) {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.setBufferSize(BUFFER_SIZE);
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            int reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                closeConnect(ftpClient);
            }
            return ftpClient;
        } catch (Exception e) {
            log.error("",e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭FTP连接
     */
    private static void closeConnect(FTPClient ftpClient) {
        if (ftpClient != null && ftpClient.isConnected()) {
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                log.error("",e);
            }
        }
    }

    /**
     * FTP服务器路径编码转换
     *
     * @param ftpPath FTP服务器路径
     * @return String
     */
    private static String changeEncoding(FTPClient ftpClient,String ftpPath) {
        String directory = null;
        try {
            if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {
                LOCAL_CHARSET = CHARSET_UTF8;
            }
            directory = new String(ftpPath.getBytes(LOCAL_CHARSET), SERVER_CHARSET);
        } catch (Exception e) {
            log.error("",e);
        }
        return directory;
    }

    /**
     * 改变工作目录
     * 如果没有,则创建工作目录
     * @param path
     */
    private static void changeAndMakeWorkingDir(FTPClient ftpClient,String path) {
        try {
            ftpClient.changeWorkingDirectory("/");
            path = path.replaceAll("\\\\","/");
            String[] path_array = path.split("/");
            for (String s : path_array) {
                boolean b = ftpClient.changeWorkingDirectory(s);
                if (!b) {
                    ftpClient.makeDirectory(s);
                    ftpClient.changeWorkingDirectory(s);
                }
            }
        } catch (IOException e) {
            log.error("",e);
            throw new RuntimeException(e);
        }
    }

    /**
     * 上传
     * @param ftpClient
     * @param filename
     * @param dirPath
     * @param in
     * @return
     */
    public static boolean upload (FTPClient ftpClient, String filename, String dirPath, InputStream in) {
        if (!ftpClient.isConnected()) {
            return false;
        }
        boolean isSuccess = false;

        if (ftpClient != null) {
            try {
                if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(OPTS_UTF8, "ON"))) {
                    LOCAL_CHARSET = CHARSET_UTF8;
                }
                ftpClient.setControlEncoding(LOCAL_CHARSET);
                String path = changeEncoding(ftpClient,dirPath);

                changeAndMakeWorkingDir(ftpClient,path);
                isSuccess = ftpClient.storeFile(new String(filename.getBytes(), SERVER_CHARSET), in);
            } catch (Exception e) {
                log.error("",e);
            } finally {
                if (in != null){
                    try{
                        in.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }
        return isSuccess;
    }

    /**
     * 下载
     * @param ftpClient
     * @param filename
     * @param dirPath
     * @param out
     * @return
     */
    public static void download (FTPClient ftpClient, String filename, String dirPath, FileOutputStream out) {
        // 登录
        if (ftpClient != null) {
            try {
                String path = changeEncoding(ftpClient,dirPath);
                changeAndMakeWorkingDir(ftpClient,path);
                String[] fileNames = ftpClient.listNames();
                if (fileNames == null || fileNames.length == 0) {
                    return;
                }
                for (String fileName : fileNames) {
                    String ftpName = new String(fileName.getBytes(SERVER_CHARSET), LOCAL_CHARSET);
                    if (StringUtils.equals(ftpName,filename)) {
                        InputStream in = ftpClient.retrieveFileStream(fileName);
                        IOUtils.copy(in,out);
                    }
                }
            } catch (IOException e) {
                log.error("",e);
            } finally {
                if (out != null){
                    try{
                        out.close();
                    }catch (IOException e){
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void main(String[] args) throws FileNotFoundException {
        FTPClient ftpClient = login("39.105.71.11",21,"zhhs_admin","eM1gDt#q2Zy4W69R");
        FileInputStream inputStream = new FileInputStream("E:\\test.txt");
        FtpUtil.upload(ftpClient,"中海测试001.txt","/data",inputStream);
        closeConnect(ftpClient);
    }
}

3、sftp

package com.zhhs.common.utils.ftp;

import com.jcraft.jsch.*;
import org.apache.commons.net.ftp.FTPClient;

import java.io.*;
import java.util.Properties;

/**
 * @author peng
 * @version 1.0
 * @date 2023-07-27 10:55
 */
public class SftpUtil {
    /**
     * 获取一个sftp链接
     * @param host sftp服务器ip
     * @param port 端口
     * @param username 用户名
     * @param password 密码
     * @return 返回ChannelSftp
     * @throws Exception 获取通道时的异常
     */
    public static ChannelSftp getSftpChannel(String host, Integer port, String username, String password) throws Exception{
        Session session;
        Channel channel = null;
        JSch jSch = new JSch();
        try {
            session = jSch.getSession(username, host, port);
            session.setPassword(password);

            // 配置链接的属性
            Properties properties = new Properties();
            properties.setProperty("StrictHostKeyChecking","no");
            session.setConfig(properties);

            // 进行sftp链接
            session.connect();

            // 获取通信通道
            channel = session.openChannel("sftp");
            channel.connect();
        } catch (JSchException e) {
            e.printStackTrace();
            throw e;
        }
        return (ChannelSftp)channel;
    }

    /**
     * 上传文件
     * @param channelSftp sftp通道
     * @param localFile 本地文件
     * @param remoteFile 远程文件
     */
    public static void upload(ChannelSftp channelSftp, String localFile, String remoteFile){
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(localFile);
            channelSftp.put(inputStream, remoteFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null){
                try{
                    inputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 从sftp服务器上下载文件
     * @param channelSftp sftp通道
     * @param remoteFile 远程文件
     * @param localFile 本地文件
     */
    public static void download(ChannelSftp channelSftp, String remoteFile, String localFile){
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(localFile);
            channelSftp.get(remoteFile, outputStream);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null){
                try{
                    outputStream.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除文件
     * @param channelSftp sftp通道
     * @param remoteFile 远程文件
     */
    public static void deleteFile(ChannelSftp channelSftp, String remoteFile) throws Exception{
        try {
            channelSftp.rm(remoteFile);
        } catch (SftpException e) {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     * 关闭sftp链接
     * @param channelSftp sftp通道
     * @throws Exception 关闭session的异常
     */
    public static void closeSession(ChannelSftp channelSftp) throws Exception{
        if(channelSftp == null){
            return;
        }

        Session session = null;
        try {
            session = channelSftp.getSession();
        } catch (JSchException e) {
            e.printStackTrace();
            throw e;
        }finally {
            if(session != null){
                session.disconnect();
            }
        }

    }

    public static void main(String[] args) throws Exception {
        ChannelSftp sftpClient =  getSftpChannel("39.105.71.11",23091,"zhhs_admin","eM1gDt#q2Zy4W69R");
        //上传
        //SftpUtil.upload(ftpClient,"E:\\test.txt","/data/中海测试.txt");
        //下载
        SftpUtil.download(sftpClient,"/data/中海测试.txt","E:\\大山测试111.txt");
        closeSession(sftpClient);
    }
}

 

标签:ftp,String,param,sftp,try,static,catch,工具,ftpClient
From: https://www.cnblogs.com/person008/p/17606064.html

相关文章

  • PinkLotar 汉化版+Mod 工具
    PinkLotar汉化 【游戏名称】:ピンクローター 【发售时间】:2010年05月01日vista/win7需要管理员权限由于使用NT技术如果NT运行出错请重新注销操作系统,然后重试https://www.rapidshare.com/files/433774827/PinkLotarcn.rarhttps://www.easy-share.com/1913138527/MOD......
  • 使用Vue+Vite搭建在线 C++ 源代码混淆工具,带在线实例
    就酱紫github开源地址:https://github.com/dffxd-suntra/cppdgithub在线实例:https://dffxd-suntra.github.io/cppd/预览图片:长截屏背景图重复了,抱歉......
  • AndroidStudio2021.3logcat工具无法显示日志解决办法
    AndroidStudio2021.3logcat工具无法显示日志解决办法 https://blog.csdn.net/weixin_43623271/article/details/127876964  1.File->setting2.搜索logcat,->ExperimentalunChkEnablenewLogcattoolwindow以后提示时Dismissit ......
  • 自动化工具之Appium元素操作小技巧
    背景   appium自动化工作中,元素操作最常用的就是Id/xpath,因为【appium1.5.0后,不支持使用name定位】所有大家在工作中使用id/xpath定位;如果还是想用name定位,需要修改源码,具体大家自己去查,但在工作中id/xpath已经够用。    今天介绍目前我工作最常用的一些方法,希望能帮......
  • Unity 编辑器选择器工具类Selection 常用函数和用法
    Unity编辑器选择器工具类Selection常用函数和用法点击封面跳转下载页面简介在Unity中,Selection类是一个非常有用的工具类,它提供了许多函数和属性,用于操作和管理编辑器中的选择对象。本文将介绍Selection类的常用函数和用法,并提供相应的示例代码。静态属性1.activeContex......
  • 69.9K Star,最强开源内网穿透工具:frp
    作为一名开发者,有很多场景需要用到内网穿透,比如:我们在接入一些大平台做第三方应用时,在本地开发微信公众号工具的时候需要让微信平台能否访问到本地提供的接口。除此之外,还有很多其他场景,也会用到,比如:把放在家里的NAS或服务器暴露到公网上,这样在外面的时候也可以随时随地的访问。......
  • Java 诊断工具 Arthas 教程学习笔记
    Java诊断工具Arthas教程学习笔记 Java诊断利器Arthas,是阿里的一款开源工具。Github-alibaba/arthas 上可以看到它的介绍。了解它,主要是最近对分析Java错误堆栈比较感兴趣,机缘巧合看到了它。本文记录的内容,就是基于它官网的文档摘抄的,涉及的截图可能由于篇幅有限,不是......
  • RVTools:vSphere第三方免费工具
    可以直观的显示每台虚拟机的信息,如CPU、内存、网络、HBA卡等,总之,通过该工具,可以使你很快的得到一份完整的虚拟化平台的数据,在后期编写文档或者作为其它项目实施时的参考信息。一、下载:RVTools最新版本4.4.3(更新时间:June23,2023)RVTools4.4.3 下载地址也放一个百度网盘链......
  • cpolar内网穿透工具知识
    科学技术的发展日新月异,电子设备在人们的生活中已成为不可或缺的工具,甚至在很多情况下,各类型的电子设备已经成为工作的核心,虽然移动设备越来越小巧,功能也越来越强大,但因其天然存在的劣势,迄今仍无法取代桌面级电脑的作用,如图片或视频编辑、文档及网站编写、软件编写、甚至家庭安保或......
  • ftp的主动模式,非20数据端口
    某银行之间ftp文件传输,修改了模式端口21,改成1021,数据传输端口就变成了1020,就是ftp端口-1FTP协议使用两个端口来处理数据传输:一个用于命令(默认为21),另一个用于数据(默认为20)。当你改变命令端口时,这并会影响数据端口。在主动模式下,FTP服务器会从它的数据端口(默认是20)向客户端的一......