SFTP工具类

丛菊两开他日泪,孤舟一系故园心
项目中,经常要用到上传文件和下载文件,这里,我们通过一个sftp连接到linux服务器。工具类如下:



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

import cmcc.gz.channel2.webServiceTo4A.controller.DataSyncImpController;
import com.jcraft.jsch.*;
import org.apache.log4j.Logger;

import javax.transaction.SystemException;

/**
 * 
 *SFTP工具类
 */
public class SFTPUtils {

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

    public      ChannelSftp channelSftp;
    public     Session  session;
    //配置文件名称,该配置文件里面设置服务器的ip地址,用户名密码等
    public String attchmentProperties = "address.properties";

    /**
     * 获取sftp连接
     * @param ftpaddress
     * @param ftpPassword
     * @param ftpUserName
     */
    public  ChannelSftp getSFTPClient(String ftpaddress, String ftpPassword,  
            String ftpUserName,String ftpPort) {
        //开始时间  用于计时    
        long startTime = System.currentTimeMillis();
        JSch jsch = new JSch();// 创建JSch对象
            Channel channel = null;
            try {
              session = jsch.getSession(ftpUserName, ftpaddress,Integer.valueOf(ftpPort)); // 根据用户名,主机ip,端口获取一个Session对象

              session.setPassword(ftpPassword); // 设置密码

              Properties config = new Properties();
              config.put("StrictHostKeyChecking", "no");
              session.setConfig(config); // 为Session对象设置properties
            //  session.setTimeout(timeout); // 设置timeout时间
              session.connect(); // 通过Session建立链接

              channel = session.openChannel("sftp"); // 打开SFTP通道
              channel.connect(); // 建立SFTP通道的连接
                long endTime = System.currentTimeMillis();
                log.debug("连接sftp耗时" + (endTime - startTime) + "毫秒");
                System.out.println("连接sftp耗时" + (endTime - startTime) + "毫秒");
                return (ChannelSftp) channel;

            } catch (Exception e) {
                e.printStackTrace();
            }
        return null;  
    }  


    /**
     * 上传文件
     */
    public boolean uploadFile(InputStream in,String fileName,String moduleName){

        try{
            //这里是从配置文件读取IP地址和用户名密码、路径,你也可以直接写在代码上
            String ftpaddress = PropertiesUtils.getSchema(attchmentProperties,"ip");
            String ftpUserName = PropertiesUtils.getSchema(attchmentProperties,"username");
            String ftpPassword = PropertiesUtils.getSchema(attchmentProperties,"password");
            String ftpPort = PropertiesUtils.getSchema(attchmentProperties,"port");
            String filePath = PropertiesUtils.getSchema(attchmentProperties,"path");
            //建立连接
            ChannelSftp channelSftp=getSFTPClient(ftpaddress,ftpPassword,ftpUserName,ftpPort);
            //判断文件夹是否存在,不存在则创建
            if (isDirExist(filePath + "/" + moduleName,channelSftp)) {
                channelSftp.put(in, filePath + "/" + moduleName + "/"+fileName);
                return true;
            } else {
                //创建文件夹在上传文件
                createDir(filePath + "/" + moduleName,channelSftp);
                channelSftp.put(in, filePath + "/" + moduleName + "/"+fileName);
                return true;
            }
        }catch(Exception e){
            e.printStackTrace();
            closeSftp();
        }
        return false;

    }

    /**
     * 读取sftp文件
     */
    public  InputStream readFile(String moudleName,String fileName){

        //这里是从配置文件读取IP地址和用户名密码、路径,你也可以直接写在代码上
        String ftpaddress = PropertiesUtils.getSchema(attchmentProperties,"ip");
        String ftpUserName = PropertiesUtils.getSchema(attchmentProperties,"username");
        String ftpPassword = PropertiesUtils.getSchema(attchmentProperties,"password");
        String ftpPort = PropertiesUtils.getSchema(attchmentProperties,"port");
        String filePath = PropertiesUtils.getSchema(attchmentProperties,"path");
        //建立连接
        ChannelSftp channelSftp=getSFTPClient(ftpaddress,ftpPassword,ftpUserName,ftpPort);

        try {
            return channelSftp.get(filePath+"/" + moudleName + "/"+fileName);
        } catch (SftpException e) {
            System.out.println("获取 :"+filePath+"/"+fileName+" 文件流错误");
            closeSftp();
        }


        return null;

    }


    /**
     * 
     * 关闭sftp
     */
    public  void closeSftp() {
         if (channelSftp != null) {
                channelSftp.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
    }
//测试
    public static void main(String[] args) {
        SFTPUtils sftpUtils = new SFTPUtils();
        try {
        //上传测试
            /*FileInputStream file = new FileInputStream("D:\\abc文档 - 副本.txt");
//          FileInputStream file = new FileInputStream("D:\\abc文档.txt");
            sftpUtils.uploadFile(file,"abc文档1.txt","ABC");
            sftpUtils.closeSftp();*/

//下载测试
            InputStream inputStream = sftpUtils.readFile("ABC","abc文档.txt");
            FileOutputStream  fos = new FileOutputStream("D:\\aaa测试qqq.txt");
            byte[]  buff = new byte[1024];
            int length = 0;
            while((length = inputStream.read(buff))!=-1){
                fos.write(buff, 0, length);
            }
            inputStream.close();
            fos.close();
            sftpUtils.closeSftp();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 创建一个文件目录
     */
    public void createDir(String createpath, ChannelSftp sftp) {
        try {
            if (isDirExist(createpath,sftp)) {
                sftp.cd(createpath);
                return;
            }
            String pathArry[] = createpath.split("/");
            StringBuffer filePath = new StringBuffer("/");
            for (String path : pathArry) {
                if (path.equals("")) {
                    continue;
                }
                filePath.append(path + "/");
                if (isDirExist(filePath.toString(),sftp)) {
                    sftp.cd(filePath.toString());
                } else {
                    // 建立目录
                    sftp.mkdir(filePath.toString());
                    // 进入并设置为当前目录
                    sftp.cd(filePath.toString());
                }
            }
            sftp.cd(createpath);
        } catch (SftpException e) {
//            throw new SystemException("创建路径错误:" + createpath);
        }
    }

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

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值