JAVA SFTP工具类

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import org.apache.commons.lang.ArrayUtils;


import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;


public class SFTPTool
{
    /**
     * 调测日志记录器。
     */
    private static final DebugLog DEBUGGER = LogFactory.getDebugLog(SFTPTool.class);

    /**
     * 运行日志记录器。
     */
    private static final IcityRuntimeLog RUNTIMELOGGER = IcityLogFactory.getRuntimeLog(SFTPTool.class);

    /**
     * Sftp客户端对象
     */
    private ChannelSftp sftp = null;

    /**
     * SFTP IP地址
     */
    private String ip;

    /**
     * SFTP 端口
     */
    private String port;

    /**
     * SFTP 用户名
     */
    private String userName;

    /**
     * SFTP 密码
     */
    private String password;

    /**
     * SFTP上传模式:BINARY
     */
    // private static final int BINARY_FILE_TYPE = 2;

    /**
     *
     * 获取实例
     *
     * @return SFTPTool newinstance实例
     *
     */
    public static SFTPTool getNewInstance()
    {
        return new SFTPTool();
    }

    /**
     * 初始化连接参数
     *
     * @param sftpIP
     *            IP
     * @param sftpPort
     *            端口
     * @param sftpUsername
     *            用户名
     * @param sftpPassword
     *            密码
     */
    public void init(String sftpIP, String sftpPort, String sftpUsername, String sftpPassword)
    {
        // 获取SFTP连接信息
        this.ip = sftpIP;
        this.port = sftpPort;
        this.userName = sftpUsername;
        this.password = sftpPassword;
    }

    /**
     * 从SFTP将符合约定命名的文件都下载到本地 .
     *
     * @param sftpDir
     *            SFTP服务器文件存放路径
     * @param locDir
     *            本地文件存放路径
     * @param regex
     *            指定文件名的格式
     * @param needBackup
     *            是否需要文件备份(true:是;false:否)
     * @param needFullMatch
     *            是否要求全局匹配(true:是;false:否)
     * @param deleteFtpFile
     *            the delete ftp file
     * @return 下载到本地的文件列表
     */
    public List<File> synSFTPFileToLocal(String sftpDir, String locDir, String regex, boolean needBackup,
            boolean needFullMatch, boolean deleteFtpFile)
    {
        List<File> files = new ArrayList<File>(KeyConstant.INITIAL_NUMBER);
        try
        {
            this.connect(ip, Integer.parseInt(this.port), userName, password);

            // 获得FTP上文件名称列表
            List<String> ftpFileNameList = this.listFiles(sftpDir, regex, needFullMatch);

            File localFile = null;

            int size = ftpFileNameList.size();

            // 根据每个FTP文件名称创建本地文件。
            for (int i = 0; i < size; i++)
            {
                // 下载源文件
                localFile = this.download(sftpDir, locDir, ftpFileNameList.get(i), deleteFtpFile);
                if (localFile.exists())
                {
                    files.add(localFile);
                }
                if (needBackup)
                {
                    // 备份源文件生成默认备份文件路径(据请求文件路径,生成同级目录的备份文件夹绝对路径)
                    String parentDir = sftpDir.substring(NumberConstant.INT_0, sftpDir.lastIndexOf("/") + 1);
                    String backupDir = parentDir + TimetaskConstants.DEFAULT_BACKUP_DIRNAME;
                    boolean bakExists = openDir(backupDir);
                    if (bakExists)
                    {
                        this.uploadFile(backupDir, localFile);
                    }
                    else
                    {
                        boolean parentExists = openDir(parentDir);
                        if (parentExists)
                        {
                            sftp.mkdir(TimetaskConstants.DEFAULT_BACKUP_DIRNAME);
                            this.uploadFile(backupDir, localFile);
                        }
                        else
                        {
                            DEBUGGER.error("sftp parentDir no exisits ");
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            DEBUGGER.error("synSFTPFileToLocal Exception", e);
        }
        finally
        {
            this.disconnect();
        }
        return files;
    }

    /**
     * 上传文件: <br>
     *
     * @param remotingPath
     *            远程路径
     * @param file
     *            本地文件
     * @param sftp
     *            sftp
     * @return 是否上传成功
     * @see
     */
    public static boolean uploadFiles(String remotingPath, File file, ChannelSftp sftp)
    {
        boolean flag = false;
        InputStream in = null;
        try
        {
            if (!openDirs(sftp, remotingPath))
            {
                sftp.mkdir(remotingPath);
            }
            sftp.cd(remotingPath);
            in = new FileInputStream(file);
            sftp.put(in, file.getName());
            if (file.exists())
            {
                flag = true;
            }
            else
            {
                flag = false;
            }
        }
        catch (Exception e)
        {
            DEBUGGER.error("uploadFile Exception : " + e);
            return false;
        }
        finally
        {
            if (null != in)
            {
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    DEBUGGER.error("IOException : " + e);
                }
            }
        }

        return flag;
    }

    /**
     * 打开指定目录
     *
     * @param sftp
     *            ChannelSftp
     * @param directory
     *            directory
     * @return 是否打开目录
     */
    public static boolean openDirs(ChannelSftp sftp, String directory)
    {
        try
        {
            sftp.cd(directory);
            return true;
        }
        catch (SftpException e)
        {
            DEBUGGER.error("openDir Exception : " + e);
            return false;
        }
    }

    /**
     * 连接sftp服务器
     *
     * @param sftpip
     *            ip地址
     * @param sftpport
     *            端口
     * @param sftpusername
     *            用户名
     * @param sftppassword
     *            密码
     * @return channelSftp
     * @throws SPMException
     */
    public ChannelSftp connect(String sftpip, int sftpport, String sftpusername, String sftppassword)
    {
        sftp = new ChannelSftp();
        try
        {
            JSch jsch = new JSch();
            jsch.getSession(sftpusername, sftpip, sftpport);
            Session sshSession = jsch.getSession(sftpusername, sftpip, sftpport);
            RUNTIMELOGGER.info("Session created");
            sshSession.setPassword(sftppassword);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            // 设置超时时间为
            sshSession.setTimeout(Integer.parseInt(StaticInitData.getFtpConnectTimeOut()) * NumberConstant.INT_1000);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;

            // 设置文件类型
            // ftpClient.setFileType(BINARY_FILE_TYPE);

            // 与防火墙相关
            // ftpClient.enterLocalPassiveMode();
        }
        catch (JSchException e)
        {
            DEBUGGER.error("JSchException : {}", e);
        }
        return sftp;
    }

    // /**
    // * 创建指定文件夹
    // *
    // * @param dirName
    // * dirName
    // */
    // public void mkDir(String dirName)
    // {
    // try
    // {
    // sftp.mkdir(dirName);
    // }
    // catch (SftpException e)
    // {
    // DEBUGGER.error("mkDir Exception : " + e);
    // }
    // }

    /**
     * 创建指定文件夹
     *
     * @param dirName
     *            dirName
     */
    public void mkDir(String dirName)
    {
        String[] dirs = dirName.split("/");
        try
        {
            String now = sftp.pwd();
            for (int i = 0; i < dirs.length; i++)
            {
                boolean dirExists = openDir(dirs[i]);
                if (!dirExists)
                {
                    sftp.mkdir(dirs[i]);
                    sftp.cd(dirs[i]);

                }

            }
            sftp.cd(now);
        }
        catch (SftpException e)
        {
            DEBUGGER.error("mkDir Exception : " + e);
        }
    }

    /**
     * 打开指定目录
     *
     * @param directory
     *            directory
     * @return 是否打开目录
     */
    public boolean openDir(String directory)
    {
        try
        {
            if (!StringTools.isNullOrNone(directory))
            {
                sftp.cd(directory);
            }
            return true;
        }
        catch (SftpException e)
        {
            DEBUGGER.error("openDir Exception : " + e);
            return false;
        }
    }

    /**
     *
     * 用sftp上传申请文档 测试报告 logo图片
     *
     * @param directory
     *            resourcePackage
     * @param singleTableModel
     *            单例模式
     * @return flag
     */
    public boolean uploadLogoFile(String directory, SingleTableModel singleTableModel)
    {
        File file = singleTableModel.getFileUpload();
        boolean flag = false;
        FileInputStream in = null;
        try
        {
            String now = sftp.pwd();
            // sftp.cd(directory);
            // add by lizhonghu 创建目录
            openAndMakeDir(directory);
            in = new FileInputStream(file);
            sftp.put(in, singleTableModel.getFileUploadFileName());
            sftp.cd(now);
            if (file.exists())
            {
                flag = true;
            }
            else
            {
                flag = false;
            }
        }
        catch (Exception e)
        {
            DEBUGGER.error("uploadFile Exception : " + e);
        }
        finally
        {
            try
            {
                if (null != in)
                {
                    try
                    {
                        in.close();
                    }
                    catch (IOException e)
                    {
                        DEBUGGER.error("IOException : " + e);
                    }
                }
            }
            catch (Exception e)
            {
                DEBUGGER.error("Exception : " + e);
            }
        }
        return flag;
    }

    /**
     * 创建指定文件夹
     *
     * @param directory
     *            路径+文件夹名
     * @return 成功与否
     */
    public boolean openAndMakeDir(String directory)
    {
        try
        {
            String now = sftp.pwd();
            if (now.equals(directory))
            {
                return true;
            }
            else
            {
                try
                {
                    if (!StringTools.isNullOrNone(directory))
                    {
                        sftp.cd(directory);
                    }
                    return true;
                }
                catch (SftpException e)
                {
                    if (directory.startsWith(now))
                    {
                        directory = directory.replaceFirst(now, "");
                    }
                    String[] dirList = directory.split("/");
                    dirList = (String[]) ArrayUtils.removeElement(dirList, "");
                    for (String dir : dirList)
                    {
                        try
                        {
                            sftp.cd(dir);
                        }
                        catch (SftpException e1)
                        {
                            sftp.mkdir(dir);
                            sftp.cd(dir);
                        }
                    }
                    return true;
                }
            }
        }
        catch (SftpException e)
        {
            DEBUGGER.error("openDir Exception : " + directory, e);
            return false;
        }
    }

    /**
     * 上传文件
     *
     * @param directory
     *            上传的目录
     * @param file
     *            要上传的文件 parentDir 上传目录的上级目录
     * @return 是否上传
     */
    public boolean uploadFile(String directory, File file)
    {
        boolean flag = false;
        FileInputStream in = null;
        try
        {
            String now = sftp.pwd();
            if (!StringTools.isNullOrNone(directory))
            {
                sftp.cd(directory);
            }
            in = new FileInputStream(file);
            sftp.put(in, file.getName());
            sftp.cd(now);
            if (file.exists())
            {
                flag = true;
            }
            else
            {
                flag = false;
            }
        }
        catch (Exception e)
        {
            DEBUGGER.error("uploadFile Exception : " + e);
        }
        finally
        {
            try
            {
                if (null != in)
                {
                    try
                    {
                        in.close();
                    }
                    catch (IOException e)
                    {
                        DEBUGGER.error("IOException : " + e);
                    }
                }
            }
            catch (Exception e)
            {
                DEBUGGER.error("Exception : " + e);
            }
        }
        return flag;
    }

    /**
     * 下载文件.
     *
     * @param ftpDir
     *            存放下载文件的SFTP路径
     * @param locDir
     *            下载的文件 SFTP上的文件名称
     * @param ftpFileName
     *            FTP上的文件名称
     * @param deleteFtpFile
     *            the delete ftp file
     * @return 本地文件对象
     * @throws FileNotFoundException
     *             FileNotFoundException
     */
    public File download(String ftpDir, String locDir, String ftpFileName, boolean deleteFtpFile)
            throws FileNotFoundException
    {
        File file = null;
        FileOutputStream output = null;
        String localDir = CommonTools.buildLocalDir(locDir).append(File.separator).append(ftpFileName).toString();
        try
        {
            String now = sftp.pwd();
            if (!StringTools.isNullOrNone(ftpDir))
            {
                sftp.cd(ftpDir);
            }
            file = new File(localDir);
            output = new FileOutputStream(file);
            sftp.get(ftpFileName, output);
            sftp.cd(now);
            if (deleteFtpFile)
            {
                sftp.rm(ftpFileName);
            }
        }
        catch (SftpException e)
        {
            if (DEBUGGER.isErrorEnable())
            {
                DEBUGGER.error("Failed to download", e);
            }
            e.toString();
        }
        finally
        {
            if (null != output)
            {
                try
                {
                    output.close();
                }
                catch (IOException e)
                {
                    DEBUGGER.error("create localFile failed:" + e);
                }
            }
        }
        return file;
    }

    /**
     * Description:断开FTP连接 <br>
     */
    public void disconnect()
    {
        if (null != sftp)
        {
            sftp.disconnect();

            if (null != sftp.getSession())
            {
                sftp.getSession().disconnect();
            }
        }
    }

    /**
     * 删除文件
     *
     * @param directory
     *            要删除文件所在目录
     * @param deleteFile
     *            要删除的文件
     * @param sftp
     */
    public void delete(String directory, String deleteFile)
    {
        try
        {
            String now = sftp.pwd();
            if (!StringTools.isNullOrNone(directory))
            {
                sftp.cd(directory);
            }
            sftp.rm(deleteFile);
            sftp.cd(now);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 列出目录下的文件
     *
     * @param directory
     *            要列出的目录
     * @param regex
     *            指定文件名的格式
     * @param needFullMatch
     *            是否要求全局匹配(true:是;false:否)
     * @return 文件列表
     * @throws SftpException
     *             SftpException
     * @throws SPMException
     *             SPMException
     */
    @SuppressWarnings("unchecked")
    public List<String> listFiles(String directory, String regex, boolean needFullMatch) throws SftpException,
            SPMException
    {
        List<String> ftpFileNameList = new ArrayList<String>(KeyConstant.INITIAL_NUMBER);
        Vector<LsEntry> sftpFile = sftp.ls(directory);
        LsEntry isEntity = null;
        String fileName = null;
        Iterator<LsEntry> sftpFileNames = sftpFile.iterator();
        while (sftpFileNames.hasNext())
        {
            isEntity = (LsEntry) sftpFileNames.next();
            fileName = isEntity.getFilename();

            if (StringTools.isNullOrNone(regex))
            {
                ftpFileNameList.add(fileName);
            }
            else
            {
                if (fileName.matches(regex))
                {
                    ftpFileNameList.add(fileName);
                }
                else
                {
                    if (needFullMatch)
                    {
                        throw new SPMException("SYSTEM ERROR",
                                "system error,all file check terminated,invalid file name " + fileName);
                    }
                    else
                    {
                        DEBUGGER.error("Invalid file named " + fileName);
                    }
                }
            }
        }

        return ftpFileNameList;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值