需要使用jar包  jsch-0.1.50.jar

sftp上传下载实现类

package com.bstek.transit.sftp;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

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;

public class SFtpClient {

    private String ftpHost;
    private int ftpPort;
    private String uploadRemotePath; //上传到的服务器目录
    private String downloadRemotePath;//从服务器哪个目录下载
    private String userName;
    private String password;
    private int timeOut = 30000;

    private Session session = null;
    private ChannelSftp channel = null;

    public SFtpClient() {
        super();
    }

    public SFtpClient(String ftpHost, int ftpPort, String uploadRemotePath, String downloadRemotePath, String userName, String password) {
        super();
        this.ftpHost = ftpHost;
        this.ftpPort = ftpPort<=0? 22:ftpPort ;
        this.uploadRemotePath = uploadRemotePath;
        this.downloadRemotePath = downloadRemotePath;
        this.userName = userName;
        this.password = password;
    }

    /**
     * 利用JSch包通过SFTP链接
     * @throws JSchException
     */
    public void connect() throws JSchException {
        try {
            JSch jsch = new JSch();
            session = jsch.getSession(userName, ftpHost, ftpPort);
            // 如果服务器连接不上,则抛出异常
            if (session == null) {
                throw new JSchException("session is null");
            }
            session.setPassword(password);// 设置密码
            session.setConfig("StrictHostKeyChecking", "no");// 设置第一次登陆的时候提示,可选值:(ask
                                                                // | yes | no)
            //设置登陆超时时间
            session.connect(timeOut);

            channel = (ChannelSftp) session.openChannel("sftp");// 创建sftp通信通道
            channel.connect(1000);

        } catch (JSchException e) {
            e.printStackTrace();
            session.disconnect();
            channel.disconnect();
            throw e;
        }

    }

    /**
     * 上传文件
     * @param localFile 本地上传文件
     * @throws SftpException
     * @throws IOException
     */
    public void uploadFile(File localFile) throws SftpException, IOException {

        String fullremoteFileName = this.uploadRemotePath + localFile.getName();
        this.uploadFile(localFile, fullremoteFileName);
    }

    public void uploadFile(File localFile, String fullremoteFileName) throws  IOException, SftpException {
        OutputStream outstream = null;
        InputStream instream = null;

        try {
            // 判断是否是文件夹
            if (!isPath(fullremoteFileName.substring(0, fullremoteFileName.lastIndexOf("/")))) {
                createPath(fullremoteFileName.substring(0, fullremoteFileName.lastIndexOf("/")));
            }

            outstream = channel.put(fullremoteFileName);
            instream = new FileInputStream(localFile);

            byte b[] = new byte[1024];
            int n;
            while ((n = instream.read(b)) != -1) {
                outstream.write(b, 0, n);
            }
            outstream.flush();

        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        } finally {
            try {
                instream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                outstream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
/**
 * 下载文件
 * @param remeotFileName
 * @param downloadLocalFile 下载到本地的文件
 * @throws SftpException
 * @throws IOException
 */
    public void downloadFile(String remeotFileName, File downloadLocalFile) throws SftpException, IOException {

        String fullremoteDownloadFileName = this.downloadRemotePath + remeotFileName;
        this.downloadFile(downloadLocalFile, fullremoteDownloadFileName);
    }

    public void downloadFile(File downloadLocalFile, String fullremoteDownloadFileName) throws  IOException, SftpException {
        OutputStream outstream = null;
        InputStream instream = null;

        try {

            instream = channel.get(fullremoteDownloadFileName);
            outstream = new FileOutputStream(downloadLocalFile);

            byte b[] = new byte[1024];
            int n;
            while ((n = instream.read(b)) != -1) {
                outstream.write(b, 0, n);
            }
            outstream.flush();

        } catch (IOException e) {
            throw e;
        }  catch (SftpException e) {
            throw e;
        }
        finally {
            try {
                if(instream!=null){
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if(outstream != null){
                    outstream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public void uploadFile(String localPath,String localFileName) throws SftpException, IOException {
        this.uploadFile(localPath,localFileName, localFileName);

    }

    public void uploadFile(String localPath,String localFileName, String remoteFileName) throws SftpException, IOException {
        String fullLocalFileName = localPath + localFileName;
        String fullremoteFileName =this.uploadRemotePath + remoteFileName;
        uploadFile(new File(fullLocalFileName), fullremoteFileName);
    }

    public void disconnect() {
        session.disconnect();
        channel.disconnect();
    }

    public void createPath(String remotePath) {
        String[] paths = remotePath.split("/");
        String currentPath;
        if (remotePath.startsWith("/")) {
            currentPath = "/";
        } else {
            currentPath = "";
        }

        for (String path : paths) {
            if ("".equals(path)) {
                continue;
            }
            currentPath += path + "/";
            try {
                channel.mkdir(currentPath);
            } catch (SftpException e) {
//                e.printStackTrace();
                // throw e;
            }
        }
    }

    public boolean isPath(String remotePath) {
        // 判断是否是文件夹
        try {
            channel.cd(channel.getHome());
            channel.cd(remotePath);
            channel.cd(channel.getHome());
            return true;
        } catch (SftpException e1) {
            // e1.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) throws IOException {
        // String ftpHost = "10.181.77.68";
        // int ftpPort = 22;
        // String localPath = "D:\\temp\\";
        // String remotePath = "usr/WebSphere/tep/";
        // String userName = "wasadm";
        // String password = "wasadm";
        //
        // SFtpClient sftp = new SFtpClient(ftpHost, ftpPort, localPath,
        // remotePath, userName, password);
        // try {
        // sftp.connect();
        // } catch (JSchException e) {
        // e.printStackTrace();
        // }
        // try {
        // sftp.uploadFile("helloworld\\pom.xml");
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
        // sftp.disconnect();
    }

}

sftp上传下载封装类

package com.bstek.transit.sftp;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.log4j.Logger;

import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;

public class SFtpTools {

    private final static Logger logger = Logger.getLogger(SFtpTools.class);

    private  String ip ;     //IP地址
    private  Integer port;    //端口
    private  String username;//用户名
    private  String password;//密码
    private  String uploadRemotePath;    //上传到服务器的路径
    private  String downloadRemotePath;    //从服务器指定路径下载

    public SFtpTools() {
        super();
    }
/**
 *
 * @param ip
 * @param port
 * @param username
 * @param password
 * @param uploadRemotePath
 * @param downloadRemotePath
 */
    public SFtpTools(String ip, Integer port, String username,String password, String uploadRemotePath,String downloadRemotePath) {
        super();
        this.ip = ip;
        this.port = port;
        this.username = username;
        this.password = password;
        this.uploadRemotePath = uploadRemotePath;
        this.downloadRemotePath = downloadRemotePath;
    }

    public void uploadFiles(File uploadFile) throws JSchException, IOException, SftpException {

        logger.info("connect to SFTP . ip:" + this.ip + "; port:" + this.port + ";uppath:" + this.uploadRemotePath + ";downpath:" + this.downloadRemotePath+ ";username:" + this.username + ";password:" + this.password);

        SFtpClient sFtpClient = new SFtpClient(ip, port, uploadRemotePath, downloadRemotePath,username, password);
        sFtpClient.connect();

        // 上传文件
        logger.info("sftp sending file....local file path = "+uploadFile.getPath());
        sFtpClient.uploadFile(uploadFile);

        // 单台链接关闭
        sFtpClient.disconnect();

    }

    /**
     * 下载文件到指定的路径
     * @param downloadFile
     * @param remeotFileName 要从服务器获取的文件名称
     * @throws JSchException
     * @throws IOException
     * @throws SftpException
     */
    public void downloadFiles(String remeotFileName, File downloadFile) throws JSchException, IOException, SftpException {

        logger.info("connect to SFTP . ip:" + this.ip + "; port:" + this.port + ";uppath:" + this.uploadRemotePath + ";downpath:" + this.downloadRemotePath+ ";username:" + this.username + ";password:" + this.password);

        SFtpClient sFtpClient = new SFtpClient(ip, port, uploadRemotePath, downloadRemotePath,username, password);
        sFtpClient.connect();

        // 下载文件
        logger.info("sftp receiving file....remote file name = "+remeotFileName);
        sFtpClient.downloadFile(remeotFileName,downloadFile);

        // 单台链接关闭
        sFtpClient.disconnect();

    }

    public static void main(String[] args) throws IOException {
//        SFtpUploadBat sfb = new SFtpUploadBat("10.181.77.68&10.181.68.236", "22&22", "D:\\temp\\", "tepppp/&teppp/",
//                "wasadm&wasadm", "wasadm&wasadm");
//        try {
//            sfb.uploadFiles("helloworld\\");
//        } catch (SftpException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        } catch (JSchException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//        }
    }

}

sftp上传下载调用

/**
     * 上传扣费文件到行方扣费系统
     * @param uploadRemotePath 服务器文件路径
     * @throws Exception
     */
    public void uploadFeeFile2Core(String currDate)  throws Exception {

        String fileName = FeeSupport.FEE_FILE_UPLOAD_PREFIX+currDate+FeeSupport.FEE_FILE_SUFFIX;
        //查询是否需要上传文件
        String hql = "from SysFileHandle where fileName = '" + fileName+"' and fileType = '"+FeeSupport.FEE_FILE_TYPE_UPLOAD+"' and handleState != '" + FeeSupport.FEE_FILE_STATE_SUCC + "'";
        SysFileHandle fileHandle = this.fileHandleDao.getFileHandleByUnique(hql);

        if(fileHandle!=null){
            // 上传
            try {
                SFtpTools sfb = new SFtpTools(sftpProperty.getIp(), sftpProperty.getPort(),sftpProperty.getUsername(),sftpProperty.getPassword(),sftpProperty.getUploadRemotePath(),sftpProperty.getDownloadRemotePath());
                sfb.uploadFiles(new File(sftpProperty.getUploadLocalPath(),fileHandle.getFileName()));
           
            } catch (Exception e) {
                fileHandle.setHandleState(FeeSupport.FEE_FILE_STATE_FAIL);
                // 更新记录状态
                this.fileHandleDao.updateFileHandle(fileHandle);
                throw e;
            }

            fileHandle.setHandleState(FeeSupport.FEE_FILE_STATE_SUCC);
            // 更新记录状态
            this.fileHandleDao.updateFileHandle(fileHandle);
        }

    }
    
public void downloadFeeFile4Core(String currDate) throws Exception {

        String fileName = FeeSupport.FEE_FILE_DOWNLOAD_PREFIX+currDate+FeeSupport.FEE_FILE_SUFFIX;
        //查询是否需要下载文件
        String hql = "from SysFileHandle where fileName = '" + fileName+"' and fileType = '"+FeeSupport.FEE_FILE_TYPE_DOWNLOAD + "'";
        SysFileHandle fileHandle = this.fileHandleDao.getFileHandleByUnique(hql);

        if(fileHandle != null && currDate.equals(fileHandle.getCreateDate())){
            return ;
        }

        if(fileHandle == null){
            fileHandle = new SysFileHandle();
            fileHandle.setFileName(fileName);
            fileHandle.setFileType(FeeSupport.FEE_FILE_TYPE_DOWNLOAD );
        }
        this.downloadFeeFile4Core(fileHandle,currDate,fileName);
    }

    private void downloadFeeFile4Core( SysFileHandle fileHandle,String currDate,String fileName) throws Exception {

        //需要下载
        try {
            SFtpTools sfb = new SFtpTools(sftpProperty.getIp(), sftpProperty.getPort(),sftpProperty.getUsername(),sftpProperty.getPassword(),sftpProperty.getUploadRemotePath(),sftpProperty.getDownloadRemotePath());
            sfb.downloadFiles(fileName,new File(sftpProperty.getDownloadLocalPath(),fileName));
       
        } catch (Exception e) {

            // 更新记录状态
            this.fileHandleDao.updateFileHandle(fileHandle);
            throw e;
        }

        fileHandle.setHandleState(FeeSupport.FEE_FILE_STATE_NO);
        fileHandle.setCreateDate(currDate);
        // 更新记录状态
        this.fileHandleDao.updateFileHandle(fileHandle);
    }
    

Java Sftp上传下载文件的更多相关文章

  1. SFTP上传下载文件、文件夹常用操作

    SFTP上传下载文件.文件夹常用操作 1.查看上传下载目录lpwd 2.改变上传和下载的目录(例如D盘):lcd  d:/ 3.查看当前路径pwd 4.下载文件(例如我要将服务器上tomcat的日志文 ...

  2. java实操之使用jcraft进行sftp上传下载文件

    sftp作为临时的文件存储位置,在某些场合还是有其应景的,比如对账文件存放.需要提供一个上传的工具类.实现方法参考下: pom.xml中引入类库: <dependency> <gro ...

  3. JAVA Sftp 上传下载

    SftpUtils package xxx;import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com ...

  4. curl实现SFTP上传下载文件

    摘自:https://blog.csdn.net/swj9099/article/details/85292444 #include <stdio.h> #include <stdl ...

  5. THINKPHP 3.2 PHP SFTP上传下载 代码实现方法

     一.SFTP介绍:使用SSH协议进行FTP传输的协议叫SFTP(安全文件传输)Sftp和Ftp都是文件传输协议.区别:sftp是ssh内含的协议(ssh是加密的telnet协议),  只要sshd服 ...

  6. java:工具(汉语转拼音,压缩包,EXCEL,JFrame窗口和文件选择器,SFTP上传下载,FTP工具类,SSH)

    1.汉语转拼音: import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuP ...

  7. Java SFTP 上传、下载等操作

    Java SFTP 上传.下载等操作 实际开发中用到了 SFTP 用于交换批量数据文件,然后琢磨了下这方面的东西,基于 JSch 写了个工具类记录下,便于日后使用. JSch是 SSH2 的纯Java ...

  8. Xshell5下利用sftp上传下载传输文件

    sftp是Secure File Transfer Protocol的缩写,安全文件传送协议.可以为传输文件提供一种安全的加密方法.sftp 与 ftp 有着几乎一样的语法和功能.SFTP 为 SSH ...

  9. SFTP远程连接服务器上传下载文件-qt4.8.0-vs2010编译器-项目实例

    本项目仅测试远程连接服务器,支持上传,下载文件,更多功能开发请看API自行开发. 环境:win7系统,Qt4.8.0版本,vs2010编译器 qt4.8.0-vs2010编译器项目实例下载地址:CSD ...

随机推荐

  1. MySQL (九)

    1 代码执行结构 代码执行结构有三种:顺序结构.分支结构和循环结构. 1.1 分支结构 分支结构:实现准备多个代码块,按照条件选择性执行某段代码. 在MySQL中只有if分支. 基本语法 if 条件判 ...

  2. 2017-04-21周C语言学习笔记

    C语言学习笔记:... --------------------------------- C语言学习笔记:学习程度的高低取决于.自学能力的高低.有的时候生活就是这样的.聪明的人有时候需要.用笨的方法 ...

  3. python 打印三级菜单

    要求: 1.用户选择城市菜单编号显示对应的下级菜单 2.可以返回上级菜单,只有在用户确定正常退出时才退出 #!/usr/bin/env python3 # -*- coding: utf-8 -*- ...

  4. Java WEB工程搭建UEditor

    1. ueditor简介: UEditor是由百度web前端研发部开发所见即所得富文本web编辑器,具有轻量,可定制,注重用户体验等特点,开源基于MIT协议,允许自由使用和修改代码... UEdito ...

  5. Django 学习笔记(五)模板标签

    关于Django模板标签官方网址https://docs.djangoproject.com/en/1.11/ref/templates/builtins/ 1.IF标签 Hello World/vi ...

  6. C# 使用NPOI 实现Excel的简单导入导出

    private void btnImport_Click(object sender, EventArgs e) { DataSet ds = new DataSet(); DataTable dt ...

  7. python注释方法以及编码问题

    一.单行注释 在python中常使用"#"来进行单行注释,其快捷键为"ctrl+/",如果要对多行代码也就是代码块进行注释时,也可以选中多行按下 "c ...

  8. Android项目实战(三十四):蓝牙4.0 BLE 多设备连接

    最近项目有个需求,手机设备连接多个蓝牙4.0 设备 并获取这些设备的数据. 查询了很多资料终于实现,现进行总结. ------------------------------------------- ...

  9. java面向对象(三)之抽象类,接口,向上转型

    java类 java类分为普通类和抽象类,接口,上一节我大概讲了java类的一般格式,今天将抽象类和接口.同时讲一下它们是怎样存储的. 最重要的是理解为什么要有抽象和接口,这样学下来你猜不会迷茫,才能 ...

  10. 文档API生成神器SandCastle使用心得

    一.功能描述 关于Sandcastle网上的参考资料相对较少,Google出来很多资料都是全英文的,相对于我这种英语渣渣看起来还是很费劲的. 言简意赅,Sandcastle主要功能是能够将C#类生成类 ...