`

sftp处理文件

    博客分类:
  • java
阅读更多

最近工作涉及sftp处理文件,写了个工具类,代码已经测试。请需要的同仁自行下载,根据自己需要,修改加工。附件有参考源码及必要jar包。

 
Java代码 
package nontax.helper; 
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 com.jcraft.jsch.Channel; 
import com.jcraft.jsch.ChannelSftp; 
import com.jcraft.jsch.JSch; 
import com.jcraft.jsch.JSchException; 
import com.jcraft.jsch.Session; 
import com.jcraft.jsch.SftpException; 
/**
* 提供SFTP处理文件服务
* @author Tonny
* @since Apr.27 2012
*
*/ 
public class SFtpHelper { 
    private  JSch jSch = null; 
    private  ChannelSftp sftp = null;//sftp主服务 
    private  Channel channel = null; 
    private  Session session = null; 
     
    private  String hostName="127.0.0.1";//远程服务器地址 
    private  int    port=22;//端口 
    private  String userName="Tonny";//用户名 
    private  String password="123";//密码 
    public SFtpHelper(String hostName, int port, String userName, 
           String password){ 
           this.hostName=hostName; 
           this.port=port; 
           this.userName=userName; 
           this.password=password; 
    } 
  
    /**
     * 连接登陆远程服务器
     * @return
     */ 
    public  boolean connect() throws Exception{ 
        try { 
            jSch= new JSch(); 
            session = jSch.getSession(userName, hostName, port); 
            session.setPassword(password); 
             
            session.setConfig(this.getSshConfig()); 
            session.connect(); 
  
            channel = session.openChannel("sftp"); 
            channel.connect(); 
  
            sftp = (ChannelSftp) channel; 
            System.out.println("登陆成功:"+sftp.getServerVersion()); 
             
        } catch (JSchException e) { 
            System.err.println("SSH方式连接FTP服务器时有JSchException异常!"); 
            System.err.println(e.getMessage()); 
            throw e; 
        } 
        return true; 
    } 
    /**
     * 关闭连接
     * @throws Exception
     */ 
    private void  disconnect() throws Exception { 
        try{ 
            if (sftp.isConnected()) { 
                sftp.disconnect(); 
            } 
            if (channel.isConnected()) { 
                channel.disconnect(); 
            } 
            if (session.isConnected()) { 
                session.disconnect(); 
            } 
        }catch(Exception e){ 
            throw e; 
        } 
     } 
      
 
    /**
     * 获取服务配置
     * @return
     */ 
    private Properties getSshConfig()throws Exception{ 
        Properties sshConfig=null; 
        try{ 
            sshConfig = new Properties(); 
            sshConfig.put("StrictHostKeyChecking", "no"); 
             
        }catch(Exception e){ 
            throw e; 
        } 
        return sshConfig; 
    } 
    /**
     * 下载远程sftp服务器文件
     * @param remotePath
     * @param remoteFilename
     * @param localFilename
     * @return
     */ 
    public  boolean downloadFile(String remotePath, 
            String remoteFilename,String localFilename)throws SftpException, 
            IOException, Exception{ 
        FileOutputStream output = null; 
        boolean success = false; 
        try { 
            if (null != remotePath && remotePath.trim() != "") { 
                sftp.cd(remotePath); 
            } 
  
            File localFile = new File(localFilename); 
            //有文件和下载文件重名 
            if (localFile.exists()) { 
                System.err.println("文件: " + localFilename + " 已经存在!"); 
                return success; 
            } 
            output = new FileOutputStream(localFile); 
            sftp.get(remoteFilename, output); 
            success = true; 
            System.out.println("成功接收文件,本地路径:"+localFilename); 
        } catch (SftpException e) { 
            System.err.println("接收文件时有SftpException异常!"); 
            System.err.println(e.getMessage()); 
            return success; 
        } catch (IOException e) { 
            System.err.println("接收文件时有I/O异常!"); 
            System.err.println(e.getMessage()); 
            return success; 
        } finally { 
            try { 
                if (null != output) { 
                    output.close(); 
                } 
                //关闭连接 
                disconnect(); 
            } catch (IOException e) { 
                System.err.println("关闭文件时出错!"); 
                System.err.println(e.getMessage()); 
            } 
        } 
        return success; 
    } 
    /**
     * 上传文件至远程sftp服务器
     * @param remotePath
     * @param remoteFilename
     * @param localFileName
     * @return
     */ 
    public  boolean uploadFile(String remotePath, 
            String remoteFilename, String localFileName)throws SftpException,Exception  { 
        boolean success = false; 
        FileInputStream fis=null; 
        try { 
            // 更改服务器目录 
            if (null != remotePath && remotePath.trim() != "") { 
                sftp.cd(remotePath); 
            } 
            File localFile = new File(localFileName); 
            fis = new FileInputStream(localFile); 
            // 发送文件 
            sftp.put(fis, remoteFilename); 
            success = true; 
            System.out.println("成功发送文件,本地路径:"+localFileName); 
        } catch (SftpException e) { 
            System.err.println("发送文件时有SftpException异常!"); 
            e.printStackTrace(); 
            System.err.println(e.getMessage()); 
            throw e; 
        } catch (Exception e) { 
            System.err.println("发送文件时有异常!"); 
            System.err.println(e.getMessage()); 
            throw e; 
        } finally { 
            try { 
                if (null != fis) { 
                    fis.close(); 
                } 
                //关闭连接 
                disconnect(); 
            } catch (IOException e) { 
                System.err.println("关闭文件时出错!"); 
                System.err.println(e.getMessage()); 
            } 
        } 
        return success; 
    } 
  
     /**
     * 上传文件至远程sftp服务器
     * @param remotePath
     * @param remoteFilename
     * @param input
     * @return
     */ 
    public  boolean uploadFile(String remotePath, 
            String remoteFilename, InputStream input)throws SftpException,Exception  { 
        boolean success = false; 
        try { 
            // 更改服务器目录 
            if (null != remotePath && remotePath.trim() != "") { 
                sftp.cd(remotePath); 
            } 
  
            // 发送文件 
            sftp.put(input, remoteFilename); 
            success = true; 
        } catch (SftpException e) { 
            System.err.println("发送文件时有SftpException异常!"); 
            e.printStackTrace(); 
            System.err.println(e.getMessage()); 
            throw e; 
        } catch (Exception e) { 
            System.err.println("发送文件时有异常!"); 
            System.err.println(e.getMessage()); 
            throw e; 
        } finally { 
            try { 
                if (null != input) { 
                    input.close(); 
                } 
                //关闭连接 
                disconnect(); 
            } catch (IOException e) { 
                System.err.println("关闭文件时出错!"); 
                System.err.println(e.getMessage()); 
            } 
     
        } 
        return success; 
    } 
    /**
     * 删除远程文件
     * @param remotePath
     * @param remoteFilename
     * @return
     * @throws Exception 
     */ 
    public  boolean deleteFile(String remotePath, String remoteFilename) throws Exception { 
        boolean success = false; 
        try { 
            // 更改服务器目录 
            if (null != remotePath && remotePath.trim() != "") { 
                sftp.cd(remotePath); 
            } 
  
            // 删除文件 
            sftp.rm(remoteFilename); 
            System.err.println("删除远程文件"+remoteFilename+"成功!"); 
            success = true; 
        } catch (SftpException e) { 
            System.err.println("删除文件时有SftpException异常!"); 
            e.printStackTrace(); 
            System.err.println(e.getMessage()); 
            return success; 
        } catch (Exception e) { 
            System.err.println("删除文件时有异常!"); 
            System.err.println(e.getMessage()); 
            return success; 
        } finally { 
            //关闭连接 
            disconnect(); 
        } 
        return success; 
    } 
 
    public String getHostName() { 
        return hostName; 
    } 
 
    public void setHostName(String hostName) { 
        this.hostName = hostName; 
    } 
 
    public int getPort() { 
        return port; 
    } 
 
    public void setPort(int port) { 
        this.port = port; 
    } 
 
    public String getUserName() { 
        return userName; 
    } 
 
    public void setUserName(String userName) { 
        this.userName = userName; 
    } 
 
    public String getPassword() { 
        return password; 
    } 
 
    public void setPassword(String password) { 
        this.password = password; 
    } 
    /**
     *测试方法
     *
     */ 
    public static void main(String [] args){ 
        try{ 
            SFtpHelper  sftp=new SFtpHelper("192.168.1.2",22,"ftp","sftp_test"); 
            System.out.println(new StringBuffer().append(" 服务器地址: ").append(sftp.getHostName()).append(" 端口:") 
                       .append(sftp.getPort()).append("用户名:").append(sftp.getUserName()).append("密码:") 
                         .append(sftp.getPassword().toString())); 
            sftp.connect(); 
//          sftp.downloadFile("\\", "test.txt", "D:\\work\\test.txt"); 
//          sftp.uploadFile("\\", "test.txt", "D:\\work\\readMe.txt"); 
//          sftp.deleteFile("\\", "test.txt"); 
        }catch(Exception e){ 
            System.out.println("异常信息:" + e.getMessage()); 
        } 
    } 

  
分享到:
评论
2 楼 zhangzh888 2014-10-29  
怎么下载 啊 都没有看见文件
1 楼 wx_hello 2014-05-07  
怎么得到文件的属性呢?  比如文件的新建时间

相关推荐

    java多例模式下处理Sftp文件上传下载

    java多例模式下处理Sftp文件上传下载,采用固定密码访问Sftp服务器。

    SFtp文件处理

    NULL 博文链接:https://forkeeps.iteye.com/blog/1501824

    PHP连接sftp并下载文件的方法教程

    sFTP(安全文件传输程序)是一种安全的交互式文件传输程序,其工作方式与 FTP(文件传输协议)类似。 然而,sFTP 比 FTP 更安全;它通过加密 SSH 传输处理所有操作。 下面这篇文章主要介绍了关于PHP连接sftp并下载...

    sftpLoad:使用 sftp 上传文件到远程服务器

    fileProcess.java:处理视频文件:1) 将一个视频文件分成 n 个块,每个块都有预定义的大小 2) 在每个块的末尾附加水平和垂直校验和数据以进行错误检测 3) 将 n 个块合并为一个文件 4)使用 mp4parser 进行 mp4 文件...

    sftp命令 交互式的文件传输程序

    是一款交互式的文件传输程序,sftp命令的运行和使用方式与ftp命令相似,但是,sftp命令对传输的所有信息使用ssh加密,它还支持公钥认证和压缩等功能。 语法格式: sftp [参数] [IP或主机名] 常用参数: -B 指定...

    Sftp2Utils.java

    JAVA通过sftp实现文件上下传,以及文件的批量处理。 登陆远程服务器,单文件上传,批量文件上传,文件下载,批量文件下载

    freeSSHd配置sftp服务器.doc

    进入Se rver status选项卡SSH server is not running 点击这里开启服务会报错:Keys not loaded or generated.,这时就是需要你手动切换到SSH选项卡,生成RSA或DSA算法文件才行,算法 文件是用于处理公有密钥的,...

    sftp-lambda:无服务器lambda函数可在AWS S3和SFTP服务器之间同步文件

    而不是第三方此解决方案适用于批量处理,不适合流式传输紧迫不需要您拉出的数据,例如,您很高兴每半小时或更不频繁地拉出一个文件便宜的比AWS Transfer for SFTP便宜便宜很多,如果你并不需要一个静态IP地址白名单...

    文件自动同步数据库管理工具

    在单位信息维护中遇到的信息系统多,数据库多,各种...文件操作任务:同步服务器上的文件,或删除服务器上的日志文件,提供文件复制后压缩和删除功能,可处理本地文件、局域网共享文件及SFTP资源文件。 已有升级版本

    sftp:go.cryptossh软件包的SFTP支持

    sftp软件包使用SFTP子系统为远程ssh服务器上的文件系统操作提供支持。 它还实现了一个SFTP服务器,用于从文件系统提供文件。 用法和示例 有关示例和用法,请参见 。 软件包的基本操作反映了软件包的功能。 用于...

    FTP 文件传输管理工具 FTPGetter Professional 5.97.0.215 中文多语免费版.zip

    通过指定文件掩码在 FTP/SFTP 服务器和本地PC之间传输多个文件。无需猜测文件名是什么!只需指定一组文件扩展名,即可轻松设置 Office 文档以进行更新,或执行所有 PHP 或 HTML 文件的预定更新。 使用文件名掩码...

    dray:云原生SFTP服务器,从S3开始,旨在支持多个数据存储后端

    Dray的目标是解决处理SFTP集成的无差别的繁重工作,因此开发人员可以专注于差异化其产品。名字叫什么托盘车是用于短距离运输重货物的手推车。 Dray将任何大小的文件传输到存储后端。 :construction: 工作正在进行中...

    文件对比工具-UltraCompare.zip(提高编程效率)

    此工具可进行文本模式,文件夹模式以及二进制模式的比较,并且可以对比较的文件进行合并,同步等操作,支持撤消操作...远程比较文件,使用 FTP/SFTP 下载远程文件,执行比较/合并操作,然后仍旧将文件保存在服务器上。

    FileZilla-Server-1.7.3-win64-免费FTP(文件传输协议)客户端软件

    支持多种协议:除了FTP,FileZilla还支持FTPS(FTP over SSL/TLS)和SFTP(SSH文件传输协议),增强了文件传输的安全性。 拖放功能:用户可以通过拖放操作,轻松上传或下载文件。 断点续传:支持大文件的断点续传...

    java+mysql简单上传下载实现

    设计sftp文件上传与下载公共类 设计定时任务,定时任务去扫描表B_REQ_INFO的状态为“待处理”的数据记录(失败可根据实际决定是否进行重试处理,重试次数等其他配置,可单独做一张表或者直接与B_SFTP_INFO配置在一起...

    FTP上传工具_LeapFTP v3.0汉化绿色单文件企业版.rar

    支持标签形式同时浏览多个 FTP 站点,引入规则设置以对目录进行高级过滤并处理副本文件,支持制作 SSL 证书,支持限速传输,支持搜索远程文件以及离线浏览,支持以浏览器远程控制。程序提供了无缝导入 CuteFTP Pro,...

    ExpanDrive_2021.8.2__TNT__xclient.info.dmg.zip

    如果大家已经受够了臃肿的云服务客户端,以及各种花哨的功能,ExpanDrive将带给我们更纯粹的文件操作体验,让处理网盘中的内容就像处理本地文件一样轻松、惬意。 将FTP/SFTP服务以及网盘像USB移动硬盘一样转载到桌面...

    Python 获取ftp服务器文件时间的方法

    ftp.retrlines('LIST',处理函数) 来获得文件的时间但是格式是 所以很难做成时间戳,获取时间的目的不就是用来比较, 所以下面个大家来个可以获取时间然后转化成时间戳的方式 首先函数 直接获取ftp文件的时间 然后...

    qt版ssh上传下载以及发命令

    1 封装了ssh的上传下载功能及发命令功能 2 提供了测试例子及界面 3 qt pro工程,用creator或vsqt加载可一键使用 4 下载时,会多一个字节的问题,进行了处理。

    免费的 FileZilla 中文版

    通过指定文件掩码在 FTP/SFTP 服务器和本地PC之间传输多个文件。无需猜测文件名是什么!只需指定一组文件扩展名,即可轻松设置 Office 文档以进行更新,或执行所有 PHP 或 HTML 文件的预定更新。 使用文件名掩码...

Global site tag (gtag.js) - Google Analytics