Java实现读取SFTP服务器指定目录文件

这篇具有很好参考价值的文章主要介绍了Java实现读取SFTP服务器指定目录文件。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

SFTP服务器的简介

SFTP(SSH File Transfer Protocol)是一种在安全通道上传输文件的协议,它是基于SSH(Secure Shell)协议的扩展,用于在客户端和服务器之间进行加密的文件传输。

SFTP 服务器的主要作用是提供一个安全的方式来上传、下载和管理文件。以下是一些 SFTP 服务器的主要作用:

  • 安全的文件传输: SFTP 使用加密通道传输数据,确保数据在传输过程中不会被窃听或篡改。这使得 SFTP
    成为一种安全的文件传输方式,适用于敏感数据或机密文件的传输。

  • 远程文件管理: SFTP
    服务器允许用户通过远程连接访问和管理服务器上的文件和目录。用户可以上传、下载、重命名、删除等操作,就像在本地操作文件一样。

  • 备份和归档: 组织可以使用 SFTP 服务器来进行文件的备份和归档。通过定期将文件上传到 SFTP
    服务器上,可以确保文件的安全存储和恢复。

  • 远程工作: SFTP 服务器使得远程工作变得更加方便。用户可以在任何地方通过 SFTP
    客户端访问和处理服务器上的文件,无需物理接触服务器。

  • 数据共享: SFTP 服务器可以用于在团队成员之间共享文件。成员可以通过 SFTP 进行文件的共享和协作,而无需将文件发送给其他人。

  • 自动化流程: SFTP 服务器可以与自动化脚本或工作流程集成,实现自动上传、下载和处理文件,从而提高工作效率。

  • 批量处理: SFTP 服务器支持批量上传和下载文件,适用于需要同时处理多个文件的场景,如数据导入、导出等。

总之,SFTP 服务器提供了一个安全、高效的方式来进行文件传输和管理,适用于许多不同的应用场景,特别是在需要保护数据安全性的情况下。文章来源地址https://www.toymoban.com/news/detail-767837.html

pom依赖

        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>${jsch.version}</version>
        </dependency>

     <jsch.version>0.1.55</jsch.version>

实现代码

import cn.hutool.core.text.CharSequenceUtil;
import com.jcraft.jsch.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Properties;

/**
 * @author Jalen
 */
public class SftpHelper {

    private static final Logger log = LoggerFactory.getLogger(SftpHelper.class);

    private ChannelSftp sftp;

    private Session session;
    /**
     * SFTP login name
     */
    private String username;
    /**
     * SFTP login password
     */
    private String password;
    /**
     * Private key
     */
    private String privateKey;
    /**
     * SFTP server ip address
     */
    private String host;
    /**
     * SFTP server port
     */
    private Integer port;

    private String directory;

    private List<String> listedFiles;

    private List<String> fileNames;

    /**
     * Construct sftp object based on password authentication
     */
    public SftpHelper(String username, String password, String host, Integer port) {
        this.username = username;
        this.password = password;
        this.host = host;
        this.port = port;
    }

    /**
     * Construct sftp object based on key authentication
     */
    public SftpHelper(String username, String host, Integer port, String privateKey) {
        this.username = username;
        this.host = host;
        this.port = port;
        this.privateKey = privateKey;
    }

    public SftpHelper() {
    }

    public List<String> getFileNames() {
        return this.fileNames;
    }

    public SftpHelper connectSftp(String filePath, String fileName) {
        SftpHelper sftp = new SftpHelper(username, password, host, port);
        sftp.login().find(filePath, fileName);
        if (!sftp.isExistsFile()) {
            log.info(" importDealerData, file no found ");
            return null;
        }
        return sftp;
    }

    /**
     * login sftp server
     */
    public SftpHelper login() {
        try {
            JSch jsch = new JSch();
            if (privateKey != null) {
                // Set private key
                jsch.addIdentity(privateKey);
            }

            session = jsch.getSession(username, host, Optional.ofNullable(port).orElse(0));

            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) {
            log.warn("sftp login failed, reason:{}", e.getMessage());
        }
        return this;
    }

    /**
     * log out
     */
    public void logout() {
        if (sftp != null) {
            if (sftp.isConnected()) {
                sftp.disconnect();
            }
        }
        if (session != null) {
            if (session.isConnected()) {
                session.disconnect();
            }
        }
    }

    /**
     * Upload the input stream data to sftp as a file. File full path = basePath + directory
     * 
     * @author Jalen
     * @date 2022/8/29 15:46
     * @param basePath
     *            basePath
     * @param directory
     *            directory
     * @param sftpFileName
     *            sftpFileName
     * @param file
     *            file
     */
    public void upload(String basePath, String directory, String sftpFileName, File file) {
        if (file == null || CharSequenceUtil.isEmpty(sftpFileName) || (CharSequenceUtil.isEmpty(basePath) && CharSequenceUtil.isEmpty(directory))) {
            log.error("upload basePath:{} directory:{} sftpFileName:{} failed, reason:{}", basePath, directory, sftpFileName, "Parameters are empty");
            return;
        }

        try {
            if (CharSequenceUtil.isNotEmpty(basePath)) {
                sftp.cd(basePath);
            }
            if (CharSequenceUtil.isNotEmpty(directory)) {
                sftp.cd(directory);
            }
        } catch (SftpException e) {
            // If the directory does not exist, create a folder
            String[] dirs = directory.split("/");
            String tempPath = basePath;
            for (String dir : dirs) {
                if (null == dir || "".equals(dir)) {
                    continue;
                }
                tempPath += "/" + dir;
                try {
                    sftp.cd(tempPath);
                } catch (SftpException ex) {
                    try {
                        sftp.mkdir(tempPath);
                        sftp.cd(tempPath);
                    } catch (SftpException sftpException) {
                        log.error("upload basePath:{} directory:{} sftpFileName:{} failed, reason:{}", basePath, directory, sftpFileName, e.getMessage());
                    }

                }
            }
        }

        InputStream input = null;
        try {
            input = new FileInputStream(file);
            sftp.put(input, sftpFileName);
        } catch (FileNotFoundException | SftpException e) {
            log.error("upload basePath:{} directory:{} sftpFileName:{} failed, reason:{}", basePath, directory, sftpFileName, e.getMessage());
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    log.error("upload basePath:{} directory:{} sftpFileName:{} failed, Reason:{}", basePath, directory, sftpFileName, e.getMessage());
                }
            }
        }
    }

    /**
     * download file.
     * 
     * @author Jalen
     * @date 2022/8/29 15:46
     * @param directory
     *            directory
     * @param downloadFile
     *            downloadFile
     * @param saveFile
     *            saveFile
     * @return boolean
     */
    public boolean download(String directory, String downloadFile, String saveFile) throws SftpException, IOException {
        FileOutputStream outPutFile = null;
        try {
            if (CharSequenceUtil.isNotEmpty(directory)) {
                sftp.cd(directory);
            }
            // The folder cannot be operated, otherwise an error will be
            // reported.
            String filepath = saveFile + downloadFile;
            File file = new File(filepath);
            outPutFile = new FileOutputStream(file.getPath());
            sftp.get(downloadFile, outPutFile);
        } catch (Exception e) {
            log.warn("download directory:{} downloadFile:{} failed, reason:{}", directory, downloadFile, e.getMessage());
            return false;
        } finally {
            if (outPutFile != null) {
                outPutFile.close();
            }
        }
        return true;
    }

    /**
     * download file
     * 
     * @author Jalen
     * @date 2022/8/29 15:47
     * @param directory
     *            directory
     * @param downloadFile
     *            downloadFile
     * @return byte[]
     */
    public byte[] download(String directory, String downloadFile) throws SftpException, IOException {
        if (CharSequenceUtil.isNotEmpty(directory)) {
            sftp.cd(directory);
        }
        InputStream is = sftp.get(downloadFile);
        return FileCopyUtils.copyToByteArray(is);
    }

    public InputStream downloadInputStream(String directory, String downloadFile) throws SftpException {
        if (CharSequenceUtil.isNotEmpty(directory)) {
            sftp.cd(directory);
        }
        return sftp.get(downloadFile);
    }

    /**
     * Delete sftp file
     * 
     * @author Jalen
     * @date 2022/8/29 15:47
     * @param directory
     *            directory
     * @param deleteFile
     *            deleteFile
     * @return boolean
     */
    public boolean delete(String directory, String deleteFile) {
        boolean flag;
        try {
            // The full path can be the directory contained in the current
            // directory
            sftp.cd(directory);
            // Delete the full suffixed file name of the file
            sftp.rm(deleteFile);
            flag = true;
        } catch (Exception e) {
            log.info("delete directory:{} deleteFile:{} failed, reason:{}", directory, deleteFile, e.getMessage());
            flag = false;
        }
        return flag;
    }

    public Boolean isValidFile(String fileName) {
        boolean isValid = false;
        if (CharSequenceUtil.isNotEmpty(fileName)) {
            String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
            boolean exist = CharSequenceUtil.isNotEmpty(fileType) && (fileType.equalsIgnoreCase(Cons.File.CSV)
                    || fileType.equalsIgnoreCase(Cons.File.XLS)
                    || fileType.equalsIgnoreCase(Cons.File.TXT)
                    || fileType.equalsIgnoreCase(Cons.File.XLSX));
            if (exist) {
                isValid = true;
            }
        }
        return isValid;
    }

    public SftpHelper find(String directory, String fileName) {
        this.directory = directory;
        this.listedFiles = listFiles(directory, fileName);
        return this;
    }

    public boolean isExistsFile() {
        return this.listedFiles != null && this.listedFiles.size() > 0;
    }

    private boolean matchFile(String target, String pattern) {
        return target.equals(pattern) || target.matches(pattern);
    }

    public List<String> listFiles(String directory, String fileName) {
        List<String> findFileList = new ArrayList<>();
        ChannelSftp.LsEntrySelector selector = lsEntry -> {
            String lsFileName = lsEntry.getFilename();
            if (CharSequenceUtil.isNotEmpty(fileName)) {
                if (matchFile(lsFileName, fileName)) {
                    findFileList.add(lsFileName);
                }
            } else {
                Boolean isValid = isValidFile(lsFileName);
                if (isValid) {
                    findFileList.add(lsFileName);
                }
            }
            return 0;
        };

        try {
            if (CharSequenceUtil.isNotEmpty(directory)) {
                sftp.ls(directory, selector);
            }
        } catch (SftpException e) {
            log.info("listFiles failed, reason:{}", e.getMessage());
        }

        return findFileList;
    }

    public String getDirectory() {
        return directory;
    }

    public void setDirectory(String directory) {
        this.directory = directory;
    }

    public List<String> getListedFiles() {
        return listedFiles;
    }

    public void setListedFiles(List<String> listedFiles) {
        this.listedFiles = listedFiles;
    }

使用案例

@RequiredArgsConstructor
@Slf4j
@Service
public class SiebelSynFileFacade {

    @Value("${spring.jpa.properties.hibernate.jdbc.batch_size:10}")
    private Integer batchSize;
    @Value("${sftp.test.host}")
    private String host;
    @Value("${sftp.test.port}")
    private Integer port;
    @Value("${sftp.test.username}")
    private String username;
    @Value("${sftp.test.password}")
    private String password;
    @Value("${sftp.test.siebelSynFile.filePath}")
    private String siebelSynFilePath;

    final AccountService accountService;
    final AccountSettingsService accountSettingsService;
    final ServiceReminderService serviceReminderService;
    final BatchService batchService;
    final AccountAreaInterestsService accountAreaInterestsService;
    final BoatService boatService;
    final EngineService engineService;


    public void synData() throws Exception {
        // Only us will synchronize data with siebel
        SftpHelper sftp = this.connectSftp(siebelSynFilePath, null);
        if (ObjectUtil.isNull(sftp)) {
            log.warn(" Files is empty. ");
            return;
        }
        List<String> listedFiles = sftp.getListedFiles();
        // CN 真实场景, 读取ftp目录
        List<BoatSynData> boatEntityList = new ArrayList<>();
        List<EngineSynData> engineEntityList = new ArrayList<>();
        List<AccountEntity> accountEntityList = new ArrayList<>();
        List<AccountSettingsEntity> accountSettingsEntityList = new ArrayList<>();
        List<AccountAreaInterestsEntity> accountAreaInterestsEntityList = new ArrayList<>();
        List<ServiceReminderEntity> serviceReminderEntityList = new ArrayList<>();
        List<ClaimEntity> claimEntityList = new ArrayList<>();
        List<CampaignEntity> campaignEntityList = new ArrayList<>();
        // CN 只读取当天文件
        for (String listedFile : listedFiles) {
            String name = listedFile;
            InputStream fileInputStream = sftp.downloadInputStream(siebelSynFilePath, listedFile);
            if (CharSequenceUtil.isBlank(name)) {
                throw new IllegalArgumentException(" Filename is not empty.");
            }
            name = name.substring(0, name.indexOf(Cons.Delimiter.UNDERSCORE));
            switch (name) {
                case SiebelCons.BOAT ->
                        boatEntityList = SynFileProxy.parseFile(name, fileInputStream, BoatSynData.class);
                case SiebelCons.ENGINE ->
                        engineEntityList = SynFileProxy.parseFile(name, fileInputStream, EngineSynData.class);
                case SiebelCons.ACCOUNT ->
                        accountEntityList = SynFileProxy.parseFile(name, fileInputStream, AccountEntity.class);
                case SiebelCons.ACCOUNT_SETTINGS ->
                        accountSettingsEntityList = SynFileProxy.parseFile(name, fileInputStream, AccountSettingsEntity.class);
                case SiebelCons.SERVICE_REMINDER ->
                        serviceReminderEntityList = SynFileProxy.parseFile(name, fileInputStream, ServiceReminderEntity.class);
                case SiebelCons.CLAIM ->
                        claimEntityList = SynFileProxy.parseFile(name, fileInputStream, ClaimEntity.class);
                case SiebelCons.AREA_INT ->
                        accountAreaInterestsEntityList = SynFileProxy.parseFile(name, fileInputStream, AccountAreaInterestsEntity.class);
                case SiebelCons.CAMPAIGN ->
                        campaignEntityList = SynFileProxy.parseFile(name, fileInputStream, CampaignEntity.class);
                default -> {
                }
            }
        }
        // CN 合并数据入库
        this.handleAccount(accountEntityList);
        this.handleAccountSettings(accountSettingsEntityList);
        this.handleReminder(serviceReminderEntityList);
        this.handleClaim(claimEntityList);
        this.handleBoat(boatEntityList);
        this.handleEngine(engineEntityList);
        this.handleAccountAreaInterests(accountAreaInterestsEntityList);
        this.handleCampaign(campaignEntityList);
        // CN 操作完成删除文件
        for (String listedFile : listedFiles) {
            sftp.delete(siebelSynFilePath, listedFile);
        }
    }


    /*------------------------------ private ------------------------------*/

    private SftpHelper connectSftp(String filePath, String fileName) {
        SftpHelper sftp = new SftpHelper(username, password, host, port);
        sftp.login().find(filePath, fileName);
        if (!sftp.isExistsFile()) {
            log.info(" importDealerData, file no found ");
            return null;
        }
        return sftp;
    }

到了这里,关于Java实现读取SFTP服务器指定目录文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

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

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

相关文章

  • shell脚本实现删除服务器指定目录下文件方法

    上述脚本中,find 命令用于查找指定目录下4天以前的文件,并将其删除。其中,-type f 表示只查找普通文件,不包括目录和符号链接等其他类型的文件;-mtime +3 表示查找修改时间早于3天前的文件;-delete 表示删除查找到的文件。 脚本中的 $folder_path 可以替换为实际的目录路径

    2023年04月19日
    浏览(44)
  • Java使用sftp文件服务器

    在工作中,对接第三方服务时,往往存在文件的传输使用,使用stfp是一种简单有效的方式,可以对文件进行上传和下载。下面是使用sftp文件服务器的demo,可以作为工具类放入项目中,即可简单上手和使用。

    2024年02月11日
    浏览(39)
  • Java从sftp服务器上传与下载文件

    业务需要从sftp服务器上上传、下载、删除文件等功能,通过查阅资料及手动敲打代码,实现了操作sftp的基本功能,有需求的小伙伴可以看看具体的实现过程。 摘自百度百科:SSH文件传输协议,是一种数据流链接,提供文件访问、传输和管理功能的网络传输协议。 SFTP允许用

    2024年02月11日
    浏览(48)
  • 通过nginx访问服务器指定目录下图片资源

    实现步骤: 1、创建文件夹并且上传图片 2、查看nginx进程 ps -ef | grep nginx    3、修改nginx配置文件 根据步骤2查看nginx安装目录;(通常nginx安装目录为 cd /usr/local/nginx/) 如果自定义的安装目录则根据实际情况而定 进入到nginx安装目录下:  1、cd /usr/local/nginx/ 2、cd conf 3、vim

    2024年02月15日
    浏览(33)
  • JAVA使用SFTP和FTP两种方式连接服务器

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

    2024年02月14日
    浏览(31)
  • 本地电脑搭建SFTP服务器,并实现公网访问

    1.1 下载 freesshd 服务器软件 下载地址:freeSSHd and freeFTPd 选择freeFTPD.exe下载 下载后,点击安装 安装之后,它会提示是否启动后台服务,Yes 安装后,点击开始菜单– freeFTPd, 注意 :这里要点击鼠标右键, 以管理员权限 打开freeFTPd,如果以普通用户打开freeFTPd, 将无法保存配置

    2024年02月08日
    浏览(47)
  • shell 脚本统计 http 文件服务器下指定目录及其子目录下所有文件的大小

    shell脚本如下: 首先 vi calculate_size.sh 写入下入内容 执行 sh calculate_size.sh http://example.com/some/dir/ 即可统计 http 文件服务器http://example.com/some/dir/ 中 dir 目录及其子目录下所有文件的大小。

    2024年02月15日
    浏览(43)
  • 宝塔 ftp 服务器发回了不可路由的地址/读取目录列表失败

    ftp连接不上: 1.注意内网IP和外网IP 2.检查ftp服务是否启动 (面板首页即可看到) 3.检查防火墙 20 端口 ftp 21 端口及被动端口 39000 - 40000 是否放行 (如是腾讯云/阿里云等还需检查安全组) 4.是否主动/被动模式都不能连接 5.新建一个用户看是否能连接 6.修改ftp配置文件 将For

    2024年01月23日
    浏览(29)
  • 怎样通过本地电脑搭建SFTP服务器,并实现公网访问?

    1.1 下载 freesshd 服务器软件 下载地址:freeSSHd and freeFTPd 选择freeFTPD.exe下载 下载后,点击安装 安装之后,它会提示是否启动后台服务,Yes 安装后,点击开始菜单– freeFTPd, 注意 :这里要点击鼠标右键, 以管理员权限 打开freeFTPd,如果以普通用户打开freeFTPd, 将无法保存配置

    2024年02月12日
    浏览(47)
  • Windows本地快速搭建SFTP文件服务器,并端口映射实现公网远程访问

    转载自cpolar极点云的文章:如何在内网搭建SFTP服务器,并发布到公网可访问 下载地址:http://www.freesshd.com/?ctt=download 选择freeFTPD.exe下载 下载后,点击安装 安装之后,它会提示是否启动后台服务,Yes 安装后,点击开始菜单– freeFTPd, 注意 :这里要点击鼠标右键, 以管理员权

    2024年02月05日
    浏览(63)

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

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

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

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

二维码1

领取红包

二维码2

领红包