`
征途2010
  • 浏览: 242693 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Sftp工具类

阅读更多
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.Vector;

import org.apache.log4j.Logger;

import com.aspire.prm.app.iodd.common.remoteclient.RemoteClient;
import com.aspire.prm.dmplt.basic.domain.FtpConfig;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;

/**
 * name:SFTPClient
 * <p>
 * </p>
 * 
 * @author:lipeng
 * @data:2014-9-22 下午04:29:45
 * @version 1.0
 */
public class SftpClient implements RemoteClient {
    
    private static final Logger logger = Logger.getLogger(SftpClient.class);
    
    private ChannelSftp sftp;
    
    private boolean isReady = false;
    
    private FtpConfig config;
    
    /** 当前工作目录,每次关闭连接要回复到null,因为当前类是单例类 */
    private String directory = null;
    
    private Session sshSession;
    
    /**
     * 连接sftp服务器
     * 
     * @param host 主机
     * @param port 端口
     * @param username 用户名
     * @param password 密码
     * @return
     */
    public SftpClient(FtpConfig config) {
        this.config = config;
        // 设置当前工作目录
        directory = config.getRootPath();
    }
    
    private void setReady() throws Exception {
        try {
            if (!isReady) {
                JSch jsch = new JSch();
                sshSession =
                    jsch.getSession(config.getUsername(), config.getServer(), Integer.parseInt(config.getPort()));
                System.out.println("Session created.");
                sshSession.setPassword(config.getPassword());
                Properties sshConfig = new Properties();
                sshConfig.put("StrictHostKeyChecking", "no");
                sshSession.setConfig(sshConfig);
                isReady = true;
            }
            if (sshSession != null && !sshSession.isConnected()) {
                sshSession.connect();
                Channel channel = sshSession.openChannel("sftp");
                channel.connect();
                sftp = (ChannelSftp) channel;
            }
            
        } catch (Exception e) {
            this.close();
            logger.error("sftp连接服务器出错,host:" + config.getServer(), e);
            throw e;
        }
    }
    
    /**
     * 上传文件
     * 
     * @param directory 上传的目录
     * @param uploadFile 要上传的文件
     * @throws Exception 
     */
    public boolean uploadFile(String uploadFile, String remoteName) throws Exception {
        try {
            setReady();
            if (remoteName.contains("/")) {
                String remotePath = remoteName.substring(0,remoteName.lastIndexOf("/"));
                try {
                    sftp.cd(directory);
                    sftp.mkdir(remotePath);
                } catch (Exception e) {
                }
                sftp.cd(directory+"/"+remotePath);
                remoteName=remoteName.substring(remoteName.lastIndexOf("/") + 1,remoteName.length());
            }else{
                sftp.cd(directory);
            }
            File file = new File(uploadFile);
            sftp.put(new FileInputStream(file), remoteName);
            return true;
        } catch (Exception e) {
            logger.error("sftp上传文件出错,directory:" + directory, e);
            throw e;
        }
    }
    
    /**
     * 下载文件
     * 
     * @param directory 下载目录
     * @param downloadFile 下载的文件
     * @param saveFile 存在本地的路径
     * @throws Exception 
     */
    public boolean downloadFile(String downloadFile, String saveFile) throws Exception {
        try {
            setReady();
            sftp.cd(directory);
            File localFile=new File(saveFile);
            if(localFile!=null&&!localFile.exists()){
                if(localFile.getParentFile()!=null&&!localFile.getParentFile().exists()){
                    localFile.getParentFile().mkdirs();
                }
                localFile.createNewFile();
            }
            sftp.get(downloadFile, new FileOutputStream(localFile));
            return true;
        } catch (Exception e) {
            logger.error("sftp下载文件出错,directory:" + directory, e);
            throw e;
        }
    }
    
    /**
     * 删除文件
     * 
     * @param deleteFile 要删除的文件
     * @throws Exception 
     */
    public boolean removeFile(String deleteFile) throws Exception {
        try {
            setReady();
            sftp.cd(directory);
            sftp.rm(deleteFile);
            return true;
        } catch (Exception e) {
            logger.error("sftp删除文件出错,directory:" + directory, e);
            throw e;
        }
    }
    
    /**
     * 
     * 复制文件
     * @param @param src
     * @param @param dst
     * @param @return
     * @param @throws Exception     
     * @return boolean
     */
    public boolean copyFile(String src,String dst) throws Exception {
        ByteArrayInputStream bStreams =null;
        try {
            setReady();
            if (!isFileExist(src)) {
                //文件不存在直接反回.
                return false;
            }
            String parentPath=dst.substring(0,dst.lastIndexOf("/"));
            if (!this.isDirExist(parentPath)) {
                createDir(parentPath);
            }
            byte[] srcFtpFileByte = inputStreamToByte(sftp.get(src));
             bStreams = new ByteArrayInputStream(srcFtpFileByte);
            //二进制流写文件
            sftp.put(bStreams, dst);
            
            return true;
        } catch (Exception e) {
            logger.error("sftp移动文件出错,[src:" + src+",dst:"+dst+"]", e);
            throw e;
        }finally{
            if(bStreams!=null){
                bStreams.close();
            }
        }
    }
    
    /**
     * 判断远程文件是否存在
     * @param srcSftpFilePath
     * @return
     * @throws SftpException
     */
    public boolean isFileExist (String srcSftpFilePath) throws SftpException {
        boolean isExitFlag = false;
        // 文件大于等于0则存在文件
        if (getFileSize(srcSftpFilePath) >= 0) {
            isExitFlag = true;
        }
        return isExitFlag;
    }
    
    /** 
     * 得到远程文件大小
     * @param srcSftpFilePath
     * @return 返回文件大小,如返回-2 文件不存在,-1文件读取异常
     * @throws SftpException
     */
    public long getFileSize (String srcSftpFilePath) throws SftpException {
        long filesize = 0;//文件大于等于0则存在
        try {
            SftpATTRS sftpATTRS = sftp.lstat(srcSftpFilePath);
            filesize = sftpATTRS.getSize();
        } catch (Exception e) {
            filesize = -1;//获取文件大小异常
            if (e.getMessage().toLowerCase().equals("no such file")) {
                filesize = -2;//文件不存在
            }
        }
        return filesize;
    }
    /**
     * inputStream类型转换为byte类型
     * @param iStrm
     * @return
     * @throws IOException
     */
    public byte[] inputStreamToByte (InputStream iStrm) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = iStrm.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }
    
    /**
     * 创建远程目录
     * @param sftpDirPath
     * @throws SftpException
     */
    public void createDir (String sftpDirPath) throws SftpException {
        sftp.cd("/");
        String pathArry[] = sftpDirPath.split("/");
        for (String path : pathArry) {
            if (path.equals("")) {
                continue;
            }
            if (isDirExist(path)) {
                sftp.cd(path);
            }
            else {
                //建立目录
                sftp.mkdir(path);
                //进入并设置为当前目录
                sftp.cd(path);
            }
        }
        sftp.cd(directory);
    }
    
    /**
     * 判断目录是否存在
     * @param directory
     * @return
     * @throws SftpException
     */
    public boolean isDirExist (String directory) throws SftpException {
        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;
    }
    /**
     * 列出目录下的文件
     * 
     * @param directory 要列出的目录
     * @return
     * @throws SftpException
     */
    public Vector<?> listFiles() throws Exception {
        setReady();
        return sftp.ls(directory);
    }
    
    public ChannelSftp getSftp() {
        return sftp;
    }
    
    public void setSftp(ChannelSftp sftp) {
        this.sftp = sftp;
    }
    
    public void close() throws IOException {
        if (sftp != null && sftp.isConnected()) {
            sftp.disconnect();
        }
        if (sshSession != null && sshSession.isConnected()) {
            sshSession.disconnect();
        }
        isReady = false;
        logger.info("JSCH session close");
        
    }
}

 

分享到:
评论

相关推荐

    SFTP工具类

    SFTP 方式 文件上传、文件下载 文件列表。。。。。。。。。

    FTP和SFTP工具类(java)

    FTP和SFTP工具类,基于java语言 其中FTP修改默认模式为被动模式 文档还包括了需要引用的maven依赖内容

    java操作sftp的工具类(JSch)

    java 实现 sftp 文件上传下载 等操作。

    连接SSH远程服务器-FTP和SFTP工具类(C#源码)

    连接SSH远程服务器,SFTP、FTP工具类。IFTP为接口,接口基本满足日常项目需要,派生MyFTPClient、MySFTPClient,方便应用扩展及整合到项目,提供例子拿来即用。sftp基于sshNet实现、Renci.SshNet是目前最为强大的C#...

    java实现sftp操作工具类

    版权声明:本工具类为个人兴趣基于chnSftp编写的应用,个人版权在先,后因各个办公环境无相关软件也有相关的个人使用,和办公环境内的推广使用,也欢迎互联网使用,如涉及相关环境认为本应用有不妥之处,请删除本人...

    SFTP上传下载文件工具

    SFTP工具,文件上传下载方便。可直接文件夹传输。

    java实现ftp和sftp的工具类

    ftp支持主动和被动模式上传下载,sftp支持上传功能

    SFTP上传工具类

    java SFTP上传工具类

    SFTP.java工具类

    sftp java工具类

    sftp上传工具之类的东东

    sftp上传工具之类的东东,需要的可以看看

    java SFTP下载工具类 可上传,下载

    需要配合com.jcraft.jsch包使用 下载地址:http://sourceforge.net/projects/jsch/files/jsch.jar/0.1.51/jsch-0.1.51.jar/download

    Ftp和Sftp上传下载工具类

    该工具支持ftp和sftp的上传和下载 1

    sftp的工具类和jar包

    sftp的jar包和一些工具类,方便使用sftp进行相关代码开发工作!

    ApacheFTP开源工具

    apache开源FTP工具,可以用于对文件的上传下载,免去了重复造轮子

    ssh2常用精简JAR

    javaee struts2 spring hibernate JAR

    Sftp操作工具类(java)&amp;jar包

    内含jar包和java实现代码 工具类含以下功能 1 得到当前工作目录地址 2 改变目录为配置的远程目录 3 取文件目录列表 4 取文件列表 5 下载文件 6 复制文件 7 删除文件 8 目录是否存在 文件是否存在 9 移动文件

    SftpDemo.rar

    提供Sftp工具类代码,提供上传、下载、删除功能。并且有详细的调用说明

    java操作sftp上传下载

    写了一个java操作sftp的工具类,里面有上传、下载、批量操作、远程创建目录、删除文件等等方法。里面的方法,都经过我测试,可用。。

    JAVA工具类

    cache EhCacheUtils - 基于ehcache的工具类 LruCacheUtils - 基于LinkedHashMap实现LRU缓存的工具类 MemcachedUtils - 基于...SFtpUtils - 操作SFTP的工具类 prop PropertiesUtils - 操作properties配置文件

Global site tag (gtag.js) - Google Analytics