• Java SFTP辅助类


    1、Maven依赖

            <dependency>
                <groupId>com.jcraft</groupId>
                <artifactId>jsch</artifactId>
                <version>0.1.54</version>
            </dependency>
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-core</artifactId>
                <version>2.9.2</version>
            </dependency>
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-core</artifactId>
                <version>2.9.2</version>
            </dependency>
            <dependency>
                <groupId>javax.validation</groupId>
                <artifactId>validation-api</artifactId>
                <version>2.0.1.Final</version>
            </dependency>

    2、创建SFTPUtils类

    package com.wap.common;
    
    import com.jcraft.jsch.*;
    import com.jcraft.jsch.ChannelSftp.LsEntry;
    import org.apache.log4j.LogManager;
    import org.apache.log4j.Logger;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.util.Properties;
    import java.util.Vector;
    
    public class SFTPUtils {
        private static final Logger LOG = LogManager.getLogger(SFTPUtils.class);
    
    
        //服务器地址
        private static String host = "192.168.1.1";
        //服务器端口
        private static int port = "22";
        //服务器账号
        private static String username = "test";
        //服务器密码
        private static String password = "test";
    
        public static String directory="/file/upload";
    
        private static ChannelSftp sftp;
    
        private static SFTPUtils instance = null;
    
        private SFTPUtils() {
        }
    
        public SFTPUtils(String directory) {
           // this.directory = directory;
        }
    
        public static SFTPUtils getInstance() {
            if (instance == null) {
                if (instance == null) {
                    instance = new SFTPUtils();
    
                    sftp = instance.connect(host, port, username, password);   //获取连接
                }
            }
            return instance;
        }
    
        /**
         * 连接sftp服务器
         *
         * @param host     主机
         * @param port     端口
         * @param username 用户名
         * @param password 密码
         * @return
         */
        public ChannelSftp connect(String host, int port, String username, String password) {
            ChannelSftp sftp = null;
            try {
                JSch jsch = new JSch();
                jsch.getSession(username, host, port);
                Session sshSession = jsch.getSession(username, host, port);
                sshSession.setPassword(password);
                Properties sshConfig = new Properties();
                sshConfig.put("StrictHostKeyChecking", "no");
                sshSession.setConfig(sshConfig);
                sshSession.connect();
                LOG.info("SFTP Session connected.");
                Channel channel = sshSession.openChannel("sftp");
                channel.connect();
                sftp = (ChannelSftp) channel;
                LOG.info("Connected to " + host);
            } catch (Exception e) {
                LOG.error(e.getMessage());
            }
            return sftp;
        }
    
        /**
         * 上传文件
         *String directory,
         * @paramdirectory  上传的目录
         * @param uploadFile 要上传的文件
         */
        public boolean upload( String uploadFile) {
            try {
                sftp.cd(directory);
                File file = new File(uploadFile);
                FileInputStream fileInputStream = new FileInputStream(file);
                sftp.put(fileInputStream, file.getName(),ChannelSftp.OVERWRITE);
                fileInputStream.close();
                return true;
            } catch (Exception e) {
                LOG.error(e.getMessage());
                return false;
            }
        }
    
        /**
         * 下载文件
         *
         * @param directory    下载目录
         * @param downloadFile 下载的文件
         * @param saveFile     存在本地的路径
         */
        public File download(String directory, String downloadFile, String saveFile) {
            try {
                sftp.cd(directory);
                File file = new File(saveFile);
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                sftp.get(downloadFile, fileOutputStream);
                fileOutputStream.close();
                return file;
            } catch (Exception e) {
                LOG.error(e.getMessage());
                return null;
            }
        }
    
        /**
         * 下载文件
         *
         * @param downloadFilePath 下载的文件完整目录
         * @param saveFile         存在本地的路径
         */
        public File download(String downloadFilePath, String saveFile) {
            try {
                int i = downloadFilePath.lastIndexOf('/');
                if (i == -1)
                    return null;
                sftp.cd(downloadFilePath.substring(0, i));
                File file = new File(saveFile);
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                sftp.get(downloadFilePath.substring(i + 1), fileOutputStream);
                fileOutputStream.close();
                return file;
            } catch (Exception e) {
                LOG.error(e.getMessage());
                return null;
            }
        }
    
        /**
         * 删除文件
         *
         * @param directory 要删除文件所在目录
         * @param deleteFile 要删除的文件
         */
        public void delete(String directory,String deleteFile) {
            try {
                sftp.cd(directory);
                sftp.rm(deleteFile);
            } catch (Exception e) {
                LOG.error(e.getMessage());
            }
        }
    
        public void disconnect() {
            try {
                sftp.getSession().disconnect();
            } catch (JSchException e) {
                LOG.error(e.getMessage());
            }
            sftp.quit();
            sftp.disconnect();
        }
    
        /**
         * 列出目录下的文件
         *
         * @param directory 要列出的目录
         * @throws SftpException
         */
        public Vector<ChannelSftp.LsEntry> listFiles(String directory) throws SftpException {
            return sftp.ls(directory);
        }
    
    
    
    
    
        public static void main(String[] args) throws IOException {
            SFTPUtils sf = SFTPUtils.getInstance();
    //        sf.upload(directory, "C:\Users\hp\Desktop\123456.png");    //上传文件
    
    //        sf.download(directory, "2.png", "C:\Users\hp\Desktop\1212.png");
            File download = sf.download("/home/1.png", "C:\Users\hp\Desktop\122221.png");
    
    //        sf.delete(directory, deleteFile); //删除文件
    
            Vector<ChannelSftp.LsEntry> files = null;        //查看文件列表
            try {
                files = sf.listFiles(directory);
            } catch (SftpException e) {
                e.printStackTrace();
            }
            for (LsEntry file : files) {
                System.out.println("###	" + file.getFilename());
            }
            sf.disconnect();
        }
    }
  • 相关阅读:
    Volar vue终极开发神器!
    Object.assign基础与实际应用场景
    如何将Promise.then中的值直接return出来
    zap linux环境下的使用
    量化
    博客园中实现代码高亮
    react环境搭建
    博客园中实现代码高亮
    Python之标准库【shutil】
    Python之标准库【shutil】
  • 原文地址:https://www.cnblogs.com/hanmian4511/p/10875044.html
Copyright © 2020-2023  润新知