`

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  
怎么得到文件的属性呢?  比如文件的新建时间

相关推荐

    SFTP上传下载文件工具

    9. **多线程支持**:FileZilla可以同时处理多个文件传输任务,提高效率。 10. **安全性**:由于使用SFTP协议,所有的文件传输都经过加密,有效防止数据泄露。 总之,SFTP上传下载文件工具如FileZilla,对于需要...

    C#sftp实现对文件的操作

    在处理完所有文件操作后,别忘了关闭连接: ```csharp ssh.Disconnect(); ``` 至于提到的"formClient",可能是指使用C#编写的一个客户端应用程序,该应用可能会有一个用户界面,用户通过这个界面与SFTP服务器交互...

    Sftp文件上传demo

    在IT行业中,SFTP(Secure File Transfer Protocol)是一种安全的文件传输协议,它允许用户在不安全的网络环境中安全地传输文件。SFTP是SSH(Secure Shell)的一部分,提供了加密的数据传输,确保了数据的隐私性和...

    JavaSFTP上传文件

    在Java编程中,SFTP(Secure File Transfer Protocol)是一种安全的文件传输协议,常用于在服务器之间或客户端与服务器之间进行文件的上传和下载。Java提供了多种库来支持SFTP操作,例如JSch(Java Secure Channel)...

    SFTP定时扫描本地文件上传到Linux服务器

    【标题】"SFTP定时扫描本地文件上传到Linux服务器"涉及的关键知识点主要集中在SFTP(Secure File Transfer Protocol)协议的使用、文件系统的监控以及自动化任务的执行。SFTP是一种安全的网络协议,用于在不同主机...

    java实现ftp、sftp的文件上传和下载

    总的来说,通过Apache Commons Net库处理FTP,和使用JSch库处理SFTP,开发者可以在Java应用中实现高效、安全的文件上传和下载功能,满足各种文件传输场景的需求。这两个库的使用极大地简化了开发过程,使得Java...

    C# SFTP上传下载文件

    这里推荐使用Renci.SshNet库,它提供了易于使用的API来处理SFTP连接、文件上传和下载。要使用这个库,你需要在项目中添加对Renci.SshNet的引用。你可以通过NuGet包管理器安装,命令为:`Install-Package Renci....

    java sftp文件上传

    Java SFTP文件上传是通过Java编程语言实现与Secure File Transfer Protocol(SFTP)服务器进行交互,将本地文件安全地传输到远程服务器的过程。SFTP是一种基于SSH的安全文件传输协议,它提供了在不安全网络上安全...

    SFtp文件处理

    标题中的“SFtp文件处理”指的是使用Secure File Transfer Protocol(SFTP)进行文件操作的相关技术。SFTP是一种安全的网络协议,用于在不同系统之间安全地传输文件,它基于SSH(Secure Shell)协议,提供了数据加密...

    c# .net sftp上传文件

    这些库为开发人员提供了简洁的API来处理SFTP连接、文件上传、下载等操作。 3. **Renci.SshNet库**: Renci.SshNet是.NET平台上广泛使用的SFTP库之一,它支持SSHv2协议,提供完整的SFTP功能。在这个项目中,可能...

    Java sftp上传文件夹demo

    在Java编程中,SFTP(Secure File Transfer Protocol)是一种安全的文件传输协议,常用于在本地系统和远程服务器之间安全地传输文件。JSch(Java Secure Channel)是一个开放源码的Java库,它实现了SSH2协议,包括...

    Windows平台c++对ftp/sftp文件和文件夹下载上传工程源代码

    在Windows平台上进行FTP(文件传输协议)和SFTP(安全文件传输协议)的文件与文件夹的下载和上传,通常需要使用特定的库来实现。本项目提供的是一套完整的C++工程源代码,包含了FTP和SFTP的客户端功能,便于开发者在...

    sftp上传下载文件的Java代码

    在Java编程环境中,SFTP(Secure File Transfer Protocol)是一种安全的文件传输协议,常用于在服务器之间或客户端与服务器之间交换文件。SFTP基于SSH(Secure Shell)协议,提供了加密的文件传输,确保数据在传输...

    windows的sftp文件管理服务器

    在IT领域,Windows操作系统上的SFTP(Secure File Transfer Protocol)文件管理服务器是一种安全的数据传输解决方案,它基于SSH(Secure Shell)协议,确保了文件传输过程中的数据加密,从而提高了安全性。...

    基于QSSH的sftp文件管理器 源代码

    【标题】基于QSSH的sftp文件管理器 源代码 在IT行业中,文件管理是日常工作中不可或缺的一部分,尤其是在远程服务器操作时。SFTP(Secure File Transfer Protocol)是一种安全的网络协议,用于在不安全的网络环境中...

    java实现sftp上传下载文件

    总结来说,Java通过jcraft库实现了SFTP协议,使得开发人员能够安全地在Java应用中处理文件的上传和下载任务。了解这些知识点并能灵活运用,将有助于你构建健壮的文件传输系统。在实际项目中,还可以考虑异常处理、...

    C#实现SFTP文件上传和下载,有进度条

    总的来说,C#和Renci.SshNet为开发人员提供了一个强大且灵活的工具集,用于处理SFTP文件操作,同时可以通过回调机制轻松地实现进度监控,提升用户体验。在你的SFTPtest工程中,你可以找到一个完整的示例,包含了编译...

    C#实现SFTP 文件上传

    在本文中,我们将深入探讨如何使用C#语言实现SFTP(Secure File Transfer Protocol)文件上传功能。SFTP是一种安全的网络协议,用于在客户端和服务器之间传输文件,它基于SSH(Secure Shell)协议,提供了数据加密和...

    SFTP上传下载 MFC VS2010

    在这个项目中,MFC被用来构建用户界面,处理SFTP操作的交互逻辑。 1. **SFTP上传**: 在上传过程中,程序首先需要连接到SFTP服务器,这通常涉及提供服务器地址、端口号、用户名和密码。然后,程序会检查本地文件...

Global site tag (gtag.js) - Google Analytics