JAVA使用SFTP和FTP两种方式连接服务器

这篇具有很好参考价值的文章主要介绍了JAVA使用SFTP和FTP两种方式连接服务器。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

区别

FTP是一种文件传输协议,一般是为了方便数据共享的。包括一个FTP服务器和多个FTP客户端。FTP客户端通过FTP协议在服务器上下载资源。FTP客户端通过FTP协议在服务器上下载资源。而一般要使用FTP需要在服务器上安装FTP服务。

而SFTP协议是在FTP的基础上对数据进行加密,使得传输的数据相对来说更安全,但是传输的效率比FTP要低,传输速度更慢(不过现实使用当中,没有发现多大差别)。SFTP和SSH使用的是相同的22端口,因此免安装直接可以使用。

总结:

一;FTP要安装,SFTP不要安装。

二;SFTP更安全,但更安全带来副作用就是的效率比FTP要低。

FtpUtil

<!--ftp文件上传-->
<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.6</version>
</dependency>
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
public class FtpUtil {
    private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);

    //ftp服务器地址
    @Value("${ftp.server}")
    private String hostname;
    //ftp服务器端口
    @Value("${ftp.port}")
    private int port;
    //ftp登录账号
    @Value("${ftp.userName}")
    private String username;
    //ftp登录密码
    @Value("${ftp.userPassword}")
    private String password;

    /**
    * 初始化FTP服务器
    *
    * @return
    */
    public FTPClient getFtpClient() {
        FTPClient ftpClient = new FTPClient();
        ftpClient.setControlEncoding("UTF-8");
        try {
            //设置连接超时时间
            ftpClient.setDataTimeout(1000 * 120);
            logger.info("连接FTP服务器中:" + hostname + ":" + port);
            //连接ftp服务器
            ftpClient.connect(hostname, port);
            //登录ftp服务器
            ftpClient.login(username, password);
            // 是否成功登录服务器
            int replyCode = ftpClient.getReplyCode();
            if (FTPReply.isPositiveCompletion(replyCode)) {
                logger.info("连接FTP服务器成功:" + hostname + ":" + port);
            } else {
                logger.error("连接FTP服务器失败:" + hostname + ":" + port);
                closeFtpClient(ftpClient);
            }
        } catch (IOException e) {
            logger.error("连接ftp服务器异常", e);
        }
        return ftpClient;
    }


    /**
     * 上传文件
     *
     * @param pathName    路径
     * @param fileName    文件名
     * @param inputStream 输入文件流
     * @return
     */
    public boolean uploadFileToFtp(String pathName, String fileName, InputStream inputStream) {
        boolean isSuccess = false;
        FTPClient ftpClient = getFtpClient();
        try {
            if (ftpClient.isConnected()) {
                logger.info("开始上传文件到FTP,文件名称:" + fileName);
                //设置上传文件类型为二进制,否则将无法打开文件
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                //路径切换,如果目录不存在创建目录
                if (!ftpClient.changeWorkingDirectory(pathName)) {
                    boolean flag = this.changeAndMakeWorkingDir(ftpClient, pathName);
                    if (!flag) {
                        logger.error("路径切换(创建目录)失败");
                        return false;
                    }
                }
                //设置被动模式,文件传输端口设置(如上传文件夹成功,不能上传文件,注释这行,否则报错refused:connect)
                ftpClient.enterLocalPassiveMode();
                ftpClient.storeFile(fileName, inputStream);
                inputStream.close();
                ftpClient.logout();
                isSuccess = true;
                logger.info(fileName + "文件上传到FTP成功");
            } else {
                logger.error("FTP连接建立失败");
            }
        } catch (Exception e) {
            logger.error(fileName + "文件上传异常", e);

        } finally {
            closeFtpClient(ftpClient);
            closeStream(inputStream);
        }
        return isSuccess;
    }

    /**
     * 删除文件
     *
     * @param pathName 路径
     * @param fileName 文件名
     * @return
     */
    public boolean deleteFile(String pathName, String fileName) {
        boolean flag = false;
        FTPClient ftpClient = getFtpClient();
        try {
            logger.info("开始删除文件");
            if (ftpClient.isConnected()) {
                //路径切换
                ftpClient.changeWorkingDirectory(pathName);
                ftpClient.enterLocalPassiveMode();
                ftpClient.dele(fileName);
                ftpClient.logout();
                flag = true;
                logger.info("删除文件成功");
            } else {
                logger.info("删除文件失败");
            }
        } catch (Exception e) {
            logger.error(fileName + "文件删除异常", e);
        } finally {
            closeFtpClient(ftpClient);
        }
        return flag;
    }

    /**
     * 关闭FTP连接
     *
     * @param ftpClient
     */
    public void closeFtpClient(FTPClient ftpClient) {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error("关闭FTP连接异常", e);
            }
        }
    }

    /**
     * 关闭文件流
     *
     * @param closeable
     */
    public void closeStream(Closeable closeable) {
        if (null != closeable) {
            try {
                closeable.close();
            } catch (IOException e) {
                logger.error("关闭文件流异常", e);
            }
        }
    }

    /**
     * 路径切换(没有则创建)
     *
     * @param ftpClient FTP服务器
     * @param path      路径
     */
    public void changeAndMakeWorkingDir(FTPClient ftpClient, String path) {
        boolean flag = false;
        try {
            String[] path_array = path.split("/");
            for (String s : path_array) {
                boolean b = ftpClient.changeWorkingDirectory(s);
                if (!b) {
                    ftpClient.makeDirectory(s);
                    ftpClient.changeWorkingDirectory(s);
                }
            }
            flag = true;
        } catch (IOException e) {
            logger.error("路径切换异常", e);
        }
        return flag;
    }

    /**
     * 从FTP下载到本地文件夹
     *
     * @param ftpClient      FTP服务器
     * @param pathName       路径
     * @param targetFileName 文件名
     * @param localPath      本地路径
     * @return
     */
    public boolean downloadFile(FTPClient ftpClient, String pathName, String targetFileName, String localPath) {
        boolean flag = false;
        OutputStream os = null;
        try {
            System.out.println("开始下载文件");
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathName);
            ftpClient.enterLocalPassiveMode();
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile file : ftpFiles) {
                String ftpFileName = file.getName();
                if (targetFileName.equalsIgnoreCase(ftpFileName)) {
                    File localFile = new File(localPath + targetFileName);
                    os = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(file.getName(), os);
                    os.close();
                }
            }
            ftpClient.logout();
            flag = true;
            logger.info("下载文件成功");
        } catch (Exception e) {
            logger.error("下载文件失败", e);
        } finally {
            closeFtpClient(ftpClient);
            closeStream(os);
        }
        return flag;
    }

}

SFTPUtil

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.54</version>
</dependency>
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;


@Component
public class SFTPUtil {
    private static final Logger logger = LoggerFactory.getLogger(SFTPUtil.class);
    private Session session = null;
    private ChannelSftp channel = null;
    private int timeout = 60000;
    
    /**
    * 连接sftp服务器
    */
    public boolean connect(String ftpUsername, String ftpAddress, int ftpPort, String ftpPassword) {
        boolean isSuccess = false;
        if (channel != null) {
            System.out.println("通道不为空");
            return false;
        }
        //创建JSch对象
        JSch jSch = new JSch();
        try {
            // 根据用户名,主机ip和端口获取一个Session对象
            session = jSch.getSession(ftpUsername, ftpAddress, ftpPort);
            //设置密码
            session.setPassword(ftpPassword);
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            //为Session对象设置properties
            session.setConfig(config);
            //设置超时
            session.setTimeout(timeout);
            //通过Session建立连接
            session.connect();
            System.out.println("Session连接成功");
            // 打开SFTP通道
            channel = (ChannelSftp) session.openChannel("sftp");
            // 建立SFTP通道的连接
            channel.connect();
            System.out.println("通道连接成功");
            isSuccess = true;
        } catch (JSchException e) {
            logger.error("连接服务器异常", e);
        }
        return isSuccess;
    }

    /**
     * 关闭连接
     */
    public void close() {
        //操作完毕后,关闭通道并退出本次会话
        if (channel != null && channel.isConnected()) {
            channel.disconnect();
        }
        if (session != null && session.isConnected()) {
            session.disconnect();
        }
    }

    /**
    * 文件上传
    * 采用默认的传输模式:OVERWRITE
    * @param src      输入流
    * @param dst      上传路径
    * @param fileName 上传文件名
    *
    * @throws SftpException
    */
    public boolean upLoadFile(InputStream src, String dst, String fileName) throws SftpException {
        boolean isSuccess = false;
        try {
            if(createDir(dst)) {
                channel.put(src, fileName);
                isSuccess = true;
            }
        } catch (SftpException e) {
            logger.error(fileName + "文件上传异常", e);
        }
        return isSuccess;
    }

    /**
    * 创建一个文件目录
    *
    * @param createpath  路径
    * @return
    */
    public boolean createDir(String createpath) {
        boolean isSuccess = false;
        try {
            if (isDirExist(createpath)) {
                channel.cd(createpath);
                return true;
            }
            String pathArry[] = createpath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for (String path : pathArry) {
                if (path.equals("")) {
                    continue;
                }
                filePath.append(path + "/");
                if (isDirExist(filePath.toString())) {
                    channel.cd(filePath.toString());
                } else {
                    // 建立目录
                    channel.mkdir(filePath.toString());
                    // 进入并设置为当前目录
                    channel.cd(filePath.toString());
                }
            }
            channel.cd(createpath);
            isSuccess = true;
        } catch (SftpException e) {
            logger.error("目录创建异常!", e);
        }
        return isSuccess;
    }

    /**
     * 判断目录是否存在
     * @param directory     路径
     * @return
     */
    public boolean isDirExist(String directory) {
        boolean isSuccess = false;
        try {
            SftpATTRS sftpATTRS = channel.lstat(directory);
            isSuccess = true;
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                isSuccess = false;
            }
        }
        return isSuccess;
    }

    /**
    * 重命名指定文件或目录
    *
    */
    public boolean rename(String oldPath, String newPath) {
        boolean isSuccess = false;
        try {
            channel.rename(oldPath, newPath);
            isSuccess = true;
        } catch (SftpException e) {
            logger.error("重命名指定文件或目录异常", e);
        }
        return isSuccess;
    }

    /**
    * 列出指定目录下的所有文件和子目录。
    */
    public Vector ls(String path) {
        try {
            Vector vector = channel.ls(path);
            return vector;
        } catch (SftpException e) {
            logger.error("列出指定目录下的所有文件和子目录。", e);
        }
        return null;
    }

    /**
    * 删除文件
    *
    * @param directory  linux服务器文件地址
    * @param deleteFile 文件名称
    */
    public boolean deleteFile(String directory, String deleteFile) {
        boolean isSuccess = false;
        try {
            channel.cd(directory);
            channel.rm(deleteFile);
            isSuccess = true;
        } catch (SftpException e) {
            logger.error("删除文件失败", e);
        }
        return isSuccess;
    }

    /**
    * 下载文件
    *
    * @param directory    下载目录
    * @param downloadFile 下载的文件
    * @param saveFile     下载到本地路径
    */
    public boolean download(String directory, String downloadFile, String saveFile) {
        boolean isSuccess = false;
        try {
            channel.cd(directory);
            File file = new File(saveFile);
            channel.get(downloadFile, new FileOutputStream(file));
            isSuccess = true;
        } catch (SftpException e) {
            logger.error("下载文件失败", e);
        } catch (FileNotFoundException e) {
            logger.error("下载文件失败", e);
        }
        return isSuccess;
    }

}

问题

 文件超出默认大小文章来源地址https://www.toymoban.com/news/detail-619655.html

#单文件上传最大大小,默认1Mb
spring.http.multipart.maxFileSize=100Mb
#多文件上传时最大大小,默认10Mb
spring.http.multipart.maxRequestSize=500MB

到了这里,关于JAVA使用SFTP和FTP两种方式连接服务器的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • SSH连接SFTP传输:如何使用libssh库在windows环境下进行(文件、文件夹)传输到远端服务器

    由于windows上的编译器一般都是没有libssh库的,所以如何我们想要使用libssh库那么我们将会使用cmake来编译libssh官网给出的源代码 libssh库下载地址: https://www.libssh.org/files/ 我们在编译libssh库之前需要先配置一些环境: a) 安装 Visual Studio 或者 MinGW b) 安装OpenSSL http://slproweb.com/p

    2024年04月24日
    浏览(50)
  • SSH连接SFTP传输:如何使用libssh库在Linux环境下进行(文件、文件夹)传输到远端服务器

    target_host :远端主机IP target_username :远端主机用户名 ssh_options_set() 函数设置会话的选项。最重要的选项是: SSH_OPTIONS_HOST:要连接到的主机的名称 SSH_OPTIONS_PORT:使用的端口(默认为端口 22) SSH_OPTIONS_USER:要连接的系统用户 SSH_OPTIONS_LOG_VERBOSITY:打印的消息数量 直接传输密

    2024年04月13日
    浏览(57)
  • sftp连接远程服务器命令

         

    2024年02月07日
    浏览(34)
  • 使用Vue脚手架配置代理服务器的两种方式

    本文主要介绍使用Vue脚手架配置代理服务器的两种方式 注意:Vue脚手架给我们提供了两种配置代理服务器的方式,各有千秋,使用的时候只能二选一,不能同时使用 除了cros和jsonp,还有一种代理方式,这种用的相对来说也很多, 一般代理服务器 这个概念很好理解,相当于生

    2024年02月02日
    浏览(62)
  • Java 两台服务器间使用FTP进行文件传输

    背景:需要把服务器A中的文件拷贝至服务器B中,要求使用FTP进行传输,当文件传输未完成时文件是tmp格式的,传输完毕后显示为原格式(此处是grib2)。

    2024年02月15日
    浏览(34)
  • vscode远程连接服务器(remote ssh)+上传本地文件到服务器(sftp)

    一、vscode远程连接服务器 1.点击vscode右边工具栏点击拓展,搜索remote ssh并安装 2.安装完成后,左边工具栏会出现一个电脑图标的远程资源管理器,点击后选择SSH TARGETS的设置 3.然后选择第一个..sshconfig 4.向服务器管理员索要服务器的连接信息并修改ssh config文件   5.设置完成

    2024年02月01日
    浏览(35)
  • Minecraft 1.20.1 Forge服务器保姆级搭建教程 (使用mcsm面板 | 两种启动方式)

    使用 Linux 云服务器部署 Minecraft 1.20.1 Forge 服务器 一台 Linux 服务器 :用来做 mc 服务器 一个用来连接服务器的终端工具(如 Xshell) :用来输入命令 Docker(可选,如果你不知道这是什么就不用管了~) 宝塔面板或 Xftp(可选,能可视化管理文件,推荐 xftp,跟 Xshell 搭配比较方

    2024年02月05日
    浏览(58)
  • ftp连接服务器报错的终极解决方案 FTP连接再无烦恼!

    AI给出的建议是: 晨希AI军师 在 主动连接 模式下,FTP客户端发起数据连接。具体过程如下: 客户端向FTP服务器的标准控制端口21发出连接请求。 服务器响应,并指示一个随机的端口(通常在1024到65535之间),用于数据传输。 客户端建立一个从本地随机端口到服务器指定的数

    2024年02月04日
    浏览(35)
  • AutoDL租用实例、配置环境、Pycharm中SSH、SFTP连接远程服务器、Pycharm访问远程服务器终端

    AutoDL链接:AutoDL 注册登录后进入控制台,左 侧容器实例 — 租用新实例 在租用实例页面:选择 计费方式 (用的不多的建议按量计费),选择合适的主机,选择要创建实例中的GPU数量(创建完后也可以增加GPU数量),选择镜像(内置了不同的深度学习框架),最后创建即可 创建

    2024年02月10日
    浏览(40)
  • 网页版 Xshell支持FTP连接和SFTP连接 【详细教程】接上篇文章

    更多创意性的开源项目 项目名称 项目简述 博客地址 远程连接 网页版的xhsell https://tanyongpeng.blog.csdn.net/article/details/122754995 人脸登录 网页版实现人脸登录 https://tanyongpeng.blog.csdn.net/article/details/125920408 easy-jenkins 一键部署工具 https://tanyongpeng.blog.csdn.net/article/details/128223343 PlumG

    2024年02月08日
    浏览(44)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包