java 连接 ftp和sftp的方式


连接工具可用

在这里插入图片描述
java 连接ftp的方式

FtpConfiguration 配置文件



package com.goboo.common.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author Administrator
 * @Classname SftpConfiguration
 * @Description 
 * @Created by lsx
 */
@Data
@Component
@ConfigurationProperties(prefix="ftp")
public class FtpConfiguration {

    /**
     * FTP服务器IP地址
     */
    private String host;
    /**
     * SFTP服务器端口
     */
    private Integer port;
    /**
     * 用户
     */
    private String username;
    /**
     * 密码
     */
    private String password;
    /**
     * 上传到文件服务器的那个目录
     */
    private String uploadDir;
    /**
     * 连接超时时间,单位毫秒
     */
    private Integer timeout;
    /**
     *  导入文件存放目录
     */
    private String sourceDirectory;
    /**
     * 默认的
     */
    private  String cron;

}

package com.goboo.modules.job.utils;

import com.goboo.common.config.FtpConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;

import java.io.IOException;
import java.io.InputStream;

/**
 * 基于JSch的Sftp工具类
 * @author lsx
 */
@Slf4j
public class FtpUtil {

    private FtpUtil() {
    }
    /**
     * @Author lsx
     * @param sftpConfiguration
     * @param inputStream
     * @param saveName
     * @return boolean
    */
    public static FTPClient upload(FtpConfiguration sftpConfiguration, InputStream inputStream, String saveName) {
        boolean flag = false;
        FTPClient ftpClient = new FTPClient();
        if (connect(ftpClient, sftpConfiguration.getHost(), sftpConfiguration.getPort(), sftpConfiguration.getUsername(), sftpConfiguration.getPassword())) {
            try {
                //2 检查工作目录是否存在
                if (ftpClient.changeWorkingDirectory(sftpConfiguration.getUploadDir())) {
                    // 3 检查是否上传成功
                    if (storeFile(ftpClient, saveName, inputStream)) {
                        flag = true;
//                        disconnect(ftpClient);
                    }
                }
            } catch (IOException e) {
                log.error("工作目录不存在");
                e.printStackTrace();
                disconnect(ftpClient);
            }
        }
        return ftpClient;
    }

    /**
     * 断开连接
     *
     * @param ftpClient
     * @throws Exception
     */
    public static void disconnect(FTPClient ftpClient) {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
                log.error("已关闭连接");
            } catch (IOException e) {
                log.error("没有关闭连接");
                e.printStackTrace();
            }
        }
    }

    /**
     * 测试是否能连接
     *
     * @param ftpClient
     * @param hostname  ip或域名地址
     * @param port      端口
     * @param username  用户名
     * @param password  密码
     * @return 返回真则能连接
     */
    public static boolean connect(FTPClient ftpClient, String hostname, int port, String username, String password) {
        boolean flag = false;
        try {
            //ftp初始化的一些参数
            ftpClient.connect(hostname, port);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            ftpClient.setControlEncoding("UTF-8");
            if (ftpClient.login(username, password)) {
                log.info("连接ftp成功");
                flag = true;
            } else {
                log.error("连接ftp失败,可能用户名或密码错误");
                try {
                    disconnect(ftpClient);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            log.error("连接失败,可能ip或端口错误");
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 上传文件
     *
     * @param ftpClient
     * @param saveName        全路径。如/home/public/a.txt
     * @param fileInputStream 要上传的文件流
     * @return
     */
    public static boolean storeFile(FTPClient ftpClient, String saveName, InputStream fileInputStream) {
        boolean flag = false;
        try {
            if (ftpClient.storeFile(saveName, fileInputStream)) {
                flag = true;
                log.error("上传成功");
            }
        } catch (IOException e) {
            log.error("上传失败");
            disconnect(ftpClient);
            e.printStackTrace();
        }
        return flag;
    }
}

上传文件调用工具类
FtpUtil.upload(sftpConfiguration, new FileInputStream(file), file.getName());

## Sftp 的连接方式


package com.dxn.utils;

import com.czinfo.framework.exception.ApplicationException;
import com.czinfo.framework.utils.SpringBeanFactory;
import com.dxn.config.BsnUriConfiguration;
import com.jcraft.jsch.*;
import lombok.extern.slf4j.Slf4j;

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

/**
 * 基于JSch的Sftp工具类
 */
@Slf4j
public class SftpUtil {
    /**
     * Session
     */
    private static Session session = null;
    /**
     * Channel
     */
    private static ChannelSftp channel = null;


    private static BsnUriConfiguration bsnUriConfiguration = SpringBeanFactory.getBean("bsnUriConfiguration");
    /**
     * 登陆SFTP服务器
     *
     * @return boolean
     */
    public static boolean login() {

        try {
            JSch jsch = new JSch();
            session = jsch.getSession(bsnUriConfiguration.getFtp().getUsername(),bsnUriConfiguration.getFtp().getHost(), bsnUriConfiguration.getFtp().getPort());
            if (bsnUriConfiguration.getFtp().getPassword() != null) {
                session.setPassword(bsnUriConfiguration.getFtp().getPassword());
            }
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.setTimeout(bsnUriConfiguration.getFtp().getTimeout());
            session.connect();
            log.debug("sftp session connected");

            log.debug("opening channel");
            channel = (ChannelSftp) session.openChannel("sftp");
            channel.connect();

            log.debug("connected successfully");
            return true;
        } catch (JSchException e) {
            log.error("sftp login failed", e);
            return false;
        }
    }

    /**
     * 登出sftp
     */
    public static void logout() {
        if (channel != null) {
            channel.quit();
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
        log.debug("logout successfully");
    }

    /**
     * 单个文件上传 (sftp目录不存在则创建后上传)
     * @param remoteFileName 远程文件名
     * @return
     */
    public  String uploadFile(String remoteFileName, OutputStream outputStream) {
        ByteArrayInputStream in = null;
        try {
            String remoteDir = bsnUriConfiguration.getFtp().getUploadDir();
            //目录不存在则创建
            createDir(remoteDir);
            String remoteFilePath =  remoteDir + "/" + remoteFileName;
            //将outputStream转换成FileInputStream
            in = ConvertUtil.parse(outputStream);
            channel.put(in, remoteFilePath);
            return remoteFilePath;
        } catch (Exception e) {
            log.error( e + "");
            throw new ApplicationException(I18nDbUtils.getI18nValue("ftp.problem"));
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 单个文件上传 (sftp目录不存在则创建后上传)
     *
     * @param remoteFileName 远程文件名
     * @param in
     * @return
     */
    public boolean uploadFile(InputStream in, String remoteFileName) {
        try {
            //目录不存在则创建后上传
            createDir(bsnUriConfiguration.getFtp().getUploadDir());
            channel.put(in, remoteFileName);
            return true;
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    /**
     * 批量上传 (sftp目录不存在则创建后上传)
     *
     * @param localPath
     * @param isDel      是否上传完成后删除 true-删除 false-不删除
     * @return
     */
    public static boolean batchUploadFile( String localPath, boolean isDel) {
        try {
            File file = new File(localPath);
            File[] files = file.listFiles();
            for (int i = 0; i < Objects.requireNonNull(files).length; i++) {
                if (files[i].isFile()
                        && !files[i].getName().contains("bak")) {
                    synchronized (localPath) {
                        /*if (uploadFile(files[i].getName(),
                                localPath, files[i].getName()) && isDel) {
                            deleteFile(localPath + files[i].getName());
                        }*/
                    }
                }
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            channel.disconnect();
        }
        return false;
    }


    /**
     * 单个文件下载 (应用目录不存在则创建后下载)
     *
     * @param remotePath
     * @param remoteFileName
     * @param localPath
     * @param localFileName
     * @return
     */
    public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
        try {
            channel.cd(remotePath);
            File file = new File(localPath + localFileName);
            mkdirs(localPath + localFileName);
            channel.get(remoteFileName, new FileOutputStream(file));
            return true;
        } catch (FileNotFoundException | SftpException e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * 判断目录存不存在,不存在则创建
     *
     * @param createpath
     * @return
     */
    public static boolean createDir(String createpath) {
        try {
            if (isDirExist(createpath)) {
                channel.cd(createpath);
                log.info(createpath);
                return true;
            }
            String[] pathArry = createpath.split("/");
            StringBuilder filePath = new StringBuilder("/");
            for (String path : pathArry) {
                if ("".equals(path)) {
                    continue;
                }
                filePath.append(path).append("/");
                createpath = filePath.toString();
                if (isDirExist(createpath)) {
                    channel.cd(createpath);
                } else {
                    channel.mkdir(createpath);
                    channel.cd(createpath);
                }
            }
            channel.cd(createpath);
            return true;
        } catch (SftpException e) {
            e.printStackTrace();
        }
        return false;
    }

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

    /**
     * 删除应用服务器文件(用于应用服务器上传SFTP文件服务器完成后)
     *
     * @param filePath
     * @return
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return false;
        }
        if (!file.isFile()) {
            return false;
        }
        return file.delete();
    }


    /**
     * 创建目录
     *
     * @param path
     */
    public static void mkdirs(String path) {
        File f = new File(path);
        String fs = f.getParent();
        f = new File(fs);
        if (!f.exists()) {
            f.mkdirs();
        }
    }
}

**

## 调用方式:

**
	 private void uploadFileFtp(List<DxnChainCode> ccList) throws ApplicationException{
        //登陆SFTP服务器
        boolean login = SftpUtil.login();
        if(!login){
            throw new ApplicationException(I18nDbUtils.getI18nValue("ftp.problem"));
        }
		 //上传后的文件路径
         new SftpUtil().uploadFile(dxnChainCode.getId() + ".zip", outputStream);
        //退出sftp
        SftpUtil.logout();
    }



***

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以通过使用Apache Commons Net库来实现FTPSFTP的登录、上传和下载功能。 对于FTP登录,首先需要建立一个FTPClient对象,并设置FTP服务器的地址、端口号、用户名和密码等登录信息。然后调用connect方法进行连接,再调用login方法进行登录验证。登录成功后,可以调用listFiles方法获取目录列表,或调用retrieveFile方法下载文件,调用storeFile方法上传文件,调用deleteFile方法删除文件,调用logout方法退出登录,最后调用disconnect方法关闭连接。 对于SFTP登录,可以使用JSch库来实现。首先需要建立一个JSch对象,并设置SFTP服务器的地址、端口号、用户名和密码等登录信息。然后调用getSession方法创建一个Session对象,并设置一些属性,如设置StrictHostKeyChecking属性为"no",以允许自动接受主机密钥。接着调用connect方法进行连接,再调用authenticate方法进行身份验证。验证成功后,可以调用getChannelSftp方法获取一个ChannelSftp对象,通过该对象可以调用ls方法获取目录列表,调用get方法下载文件,调用put方法上传文件,调用rm方法删除文件,调用exit方法退出登录,最后调用disconnect方法关闭连接。 需要注意的是,FTP是明文传输,不安全,而SFTP是使用SSH进行加密传输,相对较安全。因此,在实际应用中,建议使用SFTP来进行文件传输,以保障数据的安全性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值