sftp文件的上传与下载

import java.io.File;
import java.io.FileNotFoundException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.Vector;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

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.Session;



 /**

/**
     * 获取链接
     *
     * @return
     */
    public ChannelSftp getChannelSftp() {
        ChannelSftp sftp = null;
        try {
            String username = 。。;
            String host = 。。;
            String password = 。。;
            String port = 。。;


            sftp = connectByPassword(host, username, password, Integer.valueOf(port));
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
        return sftp;
    }


private ChannelSftp connectByPassword(String host, String username, String password, int port) {
        ChannelSftp sftp = null;

        try {
            JSch jsch = new JSch();
            Session sshSession = jsch.getSession(username, host, port);
            sshSession.setPassword(password);
            Properties sshConfig = new Properties();
            sshConfig.put("StrictHostKeyChecking", "no");
            sshSession.setConfig(sshConfig);
            sshSession.connect();
            Channel channel = sshSession.openChannel("sftp");
            channel.connect();
            sftp = (ChannelSftp) channel;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            throw new RuntimeException(e.getMessage(), e);
        }
        return sftp;
    }

/**
     * @param directory
     * @param sftp
     * @param flag:ture多层目录常见 flag:false
     *            单个目录创建,由于涉及到权限问题上级目录无法创建,所以自己实现单个目录创建,传true
     */
    public static void cdMkdir(String directory, ChannelSftp sftp, Boolean flag) {
        if (flag) {
            try {
                try {
                    sftp.cd(directory);
                } catch (SftpException sException) {
                    LOG.info(directory + " 路径不存在!");
                    if (ChannelSftp.SSH_FX_NO_SUCH_FILE == sException.id) {
                        sftp.mkdir(directory);
                        sftp.cd(directory);
                        LOG.info(directory + " 路径已创建!");
                    }
                }
            } catch (SftpException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        } else {
            try {
            	String now = sftp.pwd();
            	directory = directory.substring(now.length());
            	String[] dirs = directory.split("/");
                for (int i = 1; i < dirs.length; i++) {
                    boolean dirExists = openDir(dirs[i], sftp);
                    if (!dirExists) {
                        sftp.mkdir(dirs[i]);
                        sftp.cd(dirs[i]);
                        LOG.info(dirs[i] + " 路径已创建!");
                    }

                }
                sftp.cd(now);
            } catch (SftpException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }

    }
/**
     * 上传文件
     * 
     * @param remotePath 上传的目录
     * @param localPath 要上传的文件
     * @param sftp
     */
    public static void upload(String remotePath, String localPath, ChannelSftp sftp) {
        LOG.info("upload file remotePath:{},localPath:{}", remotePath, localPath);
        FileInputStream fis = null;
        try {
            sftp.cd(remotePath);
            File file = new File(localPath);
            fis = new FileInputStream(file);
            sftp.put(fis, file.getName());
        } catch (Exception e) {
            LOG.error("upload file error:{}", e);
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(fis);
            //sftp.disconnect();
        }
    }

/**
*上传文件到ftp
*/ 
@Override
    public boolean upload(InvestmentChannelTypeEnum channelType, Long productNo, Date date, FileNameEnum an) {
        ChannelSftp sftp = null;
        try {
            //本地地址
            String localAbsolutePath = "....";

            //root地址
            String remoteRootPath = ".......";

            sftp = getChannelSftp(channelType);
            SftpUtil.cdMkdir(remoteRootPath, sftp, SftpUtil.openDir(remoteRootPath, sftp));
            SftpUtil.upload(remoteRootPath, localAbsolutePath, sftp);
            return true;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        } finally {
            if (sftp != null) {
                sftp.disconnect();
            }
        }
        return false;
    }

/**
     * 下载文件
     * 
     * @param remotePath 下载完整目录
     * @param remoteFileName 下载的文件名称
     * @param localPath 存在本地的完整路径
     * @param sftp
     */
    public static void download(String remotePath, String remoteFileName, String localPath, ChannelSftp sftp) {

        FileOutputStream fos = null;
        try {
            sftp.cd(remotePath);
            File file = new File(localPath);
            (file.getParentFile()).mkdirs();
            fos = new FileOutputStream(file);
            sftp.get(remoteFileName, fos);
        } catch (Exception e) {
            LOG.error("down load file error:{}", e);
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(fos);
            // sftp.disconnect();
        }
    }

    /**
     * 删除文件
     * 
     * @param directory 要删除文件所在目录
     * @param deleteFile 要删除的文件
     * @param sftp
     */
    public static void delete(String directory, String deleteFile, ChannelSftp sftp) {
        try {
            boolean flag = true;
            sftp.cd(directory);
            try {
                sftp.rm(deleteFile);
            } catch (SftpException sException) {
                if (ChannelSftp.SSH_FX_NO_SUCH_FILE == sException.id) {
                    flag = false;
                }
            }
            if (flag) {
                LOG.info(directory + deleteFile + " 文件已删除!");
            } else {
                LOG.info(directory + deleteFile + " 文件不存在,无需删除!");
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            //sftp.disconnect();
        }
    }


/**
     * 打开指定目录
     * 
     * @param directory directory
     * @return 是否打开目录
     */
    public static boolean openDir(String directory, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            return true;
        } catch (SftpException e) {
            LOG.info(directory + " 路径不存在!");
            return false;
        }
    }

    /**
     * 查看文件是否存在
     * 
     * @param directory:远程目录
     * @param sftp
     * @param fileName
     * @param flag:ture多层目录常见 flag:false
     * @return
     * @throws
     */
    public static boolean fileIsExist(String directory, String fileName, ChannelSftp sftp) {
        boolean exits = true;
        try {
            boolean dirExists = openDir(directory, sftp);
            if (!dirExists) {
                sftp.mkdir(directory);
            }
            sftp.cd(directory);
            sftp.ls(fileName);
        } catch (SftpException sException) {
            exits = false;
            if (ChannelSftp.SSH_FX_NO_SUCH_FILE == sException.id) {
                LOG.info("文件不存在!path:" + directory + File.separator + fileName);
            }
        }
        return exits;
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值