添加依赖Jsch-0.1.54.jar

<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version></version>
</dependency>

FTP上传下载文件例子

import sun.net.ftp.FtpClient;
import sun.net.ftp.FtpProtocolException;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.SocketAddress;

/**
 * Java自带的API对FTP的操作
 */
public class Test {
    private FtpClient ftpClient;

    Test(){
         /*
        使用默认的端口号、用户名、密码以及根目录连接FTP服务器
         */
        , ", "/home/jiashubing/ftp/anonymous/");
    }

    public void connectServer(String ip, int port, String user, String password, String path) {
        try {
            /* ******连接服务器的两种方法*******/
            ftpClient = FtpClient.create();
            try {
                SocketAddress addr = new InetSocketAddress(ip, port);
                ftpClient.connect(addr);
                ftpClient.login(user, password.toCharArray());
                System.out.println("login success!");
                ) {
                    //把远程系统上的目录切换到参数path所指定的目录
                    ftpClient.changeDirectory(path);
                }
            } catch (FtpProtocolException e) {
                e.printStackTrace();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }

    /**
     * 关闭连接
     */
    public void closeConnect() {
        try {
            ftpClient.close();
            System.out.println("disconnect success");
        } catch (IOException ex) {
            System.out.println("not disconnect");
            ex.printStackTrace();
            throw new RuntimeException(ex);
        }
    }

    /**
     * 上传文件
     * @param localFile 本地文件
     * @param remoteFile 远程文件
     */
    public void upload(String localFile, String remoteFile) {
        File file_in = new File(localFile);
        try(OutputStream os = ftpClient.putFileStream(remoteFile);
            FileInputStream is = new FileInputStream(file_in)) {
            ];
            int c;
            ) {
                os.write(bytes, , c);
            }
            System.out.println("upload success");
        } catch (IOException ex) {
            System.out.println("not upload");
            ex.printStackTrace();
        } catch (FtpProtocolException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载文件。获取远程机器上的文件filename,借助TelnetInputStream把该文件传送到本地。
     * @param remoteFile 远程文件路径(服务器端)
     * @param localFile 本地文件路径(客户端)
     */
    public void download(String remoteFile, String localFile) {
        File file_in = new File(localFile);
        try(InputStream is = ftpClient.getFileStream(remoteFile);
            FileOutputStream os = new FileOutputStream(file_in)){

            ];
            int c;
            ) {
                os.write(bytes, , c);
            }
            System.out.println("download success");
        } catch (IOException ex) {
            System.out.println("not download");
            ex.printStackTrace();
        }catch (FtpProtocolException e) {
            e.printStackTrace();
        }
    }

    public static void main(String agrs[]) {
        Test fu = new Test();

        //下载测试
        String filepath[] = {"aa.xlsx","bb.xlsx"};
        String localfilepath[] = {"E:/lalala/aa.xlsx","E:/lalala/bb.xlsx"};
        ; i < filepath.length; i++) {
            fu.download(filepath[i], localfilepath[i]);
        }

        //上传测试
        String localfile = "E:/lalala/tt.xlsx";
        String remotefile = "tt.xlsx";                //上传
        fu.upload(localfile, remotefile);
        fu.closeConnect();

    }

}

SFTP上传下载文件例子

package com;

import com.jcraft.jsch.*;

import java.util.Properties;

/**
 * 解释一下SFTP的整个调用过程,这个过程就是通过Ip、Port、Username、Password获取一个Session,
 * 然后通过Session打开SFTP通道(获得SFTP Channel对象),再在建立通道(Channel)连接,最后我们就是
 * 通过这个Channel对象来调用SFTP的各种操作方法.总是要记得,我们操作完SFTP需要手动断开Channel连接与Session连接。
 * @author jiashubing
 * @since 2018/5/8
 */
public class SftpCustom {

    private ChannelSftp channel;
    private Session session;
    private String sftpPath;

    SftpCustom() {
         /*
         使用端口号、用户名、密码以连接SFTP服务器
         */
        , ", "/home/ftp/");
    }

    SftpCustom(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String sftpPath) {
        this.connectServer(ftpHost, ftpPort, ftpUserName, ftpPassword, sftpPath);
    }

    public void connectServer(String ftpHost, int ftpPort, String ftpUserName, String ftpPassword, String sftpPath) {
        try {
            this.sftpPath = sftpPath;

            // 创建JSch对象
            JSch jsch = new JSch();
            // 根据用户名,主机ip,端口获取一个Session对象
            session = jsch.getSession(ftpUserName, ftpHost, ftpPort);
            if (ftpPassword != null) {
                // 设置密码
                session.setPassword(ftpPassword);
            }
            Properties configTemp = new Properties();
            configTemp.put("StrictHostKeyChecking", "no");
            // 为Session对象设置properties
            session.setConfig(configTemp);
            // 设置timeout时间
            session.setTimeout();
            session.connect();
            // 通过Session建立链接
            // 打开SFTP通道
            channel = (ChannelSftp) session.openChannel("sftp");
            // 建立SFTP通道的连接
            channel.connect();
        } catch (JSchException e) {
            //throw new RuntimeException(e);
        }
    }

    /**
     * 断开SFTP Channel、Session连接
     */
    public void closeChannel() {
        try {
            if (channel != null) {
                channel.disconnect();
            }
            if (session != null) {
                session.disconnect();
            }
        } catch (Exception e) {
            //
        }
    }

    /**
     * 上传文件
     *
     * @param localFile  本地文件
     * @param remoteFile 远程文件
     */
    public void upload(String localFile, String remoteFile) {
        try {
            remoteFile = sftpPath + remoteFile;
            channel.put(localFile, remoteFile, ChannelSftp.OVERWRITE);
            channel.quit();
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载文件
     *
     * @param remoteFile 远程文件
     * @param localFile  本地文件
     */
    public void download(String remoteFile, String localFile) {
        try {
            remoteFile = sftpPath + remoteFile;
            channel.get(remoteFile, localFile);
            channel.quit();
        } catch (SftpException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SftpCustom sftpCustom = new SftpCustom();
        //上传测试
        String localfile = "E:/logs/catalina.out";
        String remotefile = "catalina.out";
        sftpCustom.upload(localfile, remotefile);

        //下载测试
//        sftpCustom.download(remotefile, "E:/lalala/catalina.out");
//        sftpCustom.closeChannel();
    }

}

Java实现FTP与SFTP文件上传下载的更多相关文章

  1. Java实现FTP批量大文件上传下载篇1

    本文介绍了在Java中,如何使用Java现有的可用的库来编写FTP客户端代码,并开发成Applet控件,做成基于Web的批量.大文件的上传下载控件.文章在比较了一系列FTP客户库的基础上,就其中一个比 ...

  2. 我的代码库-Java8实现FTP与SFTP文件上传下载

    有网上的代码,也有自己的理解,代码备份 一般连接windows服务器使用FTP,连接linux服务器使用SFTP.linux都是通过SFTP上传文件,不需要额外安装,非要使用FTP的话,还得安装FTP ...

  3. java操作FTP,实现文件上传下载删除操作

    上传文件到FTP服务器: /** * Description: 向FTP服务器上传文件 * @param url FTP服务器hostname * @param port FTP服务器端口,如果默认端 ...

  4. Java 客户端操作 FastDFS 实现文件上传下载替换删除

    FastDFS 的作者余庆先生已经为我们开发好了 Java 对应的 SDK.这里需要解释一下:作者余庆并没有及时更新最新的 Java SDK 至 Maven 中央仓库,目前中央仓库最新版仍旧是 1.2 ...

  5. Jsch - java SFTP 文件上传下载

    使用Jsch上传.下载文件,核心步骤是:获取channel,然后使用get/put方法下载.上传文件 核心代码句: session = jSch.getSession(ftpUserName, ftp ...

  6. JAVA中使用FTPClient实现文件上传下载

    在JAVA程序中,经常需要和FTP打交道,比如向FTP服务器上传文件.下载文件,本文简单介绍如何利用jakarta commons中的FTPClient(在commons-net包中)实现上传下载文件 ...

  7. JAVA中使用FTPClient实现文件上传下载实例代码

    一.上传文件 原理就不介绍了,大家直接看代码吧 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 ...

  8. linux命令行模式下对FTP服务器进行文件上传下载

    参考源:点击这里查看   1. 连接ftp服务器 格式:ftp [hostname| ip-address]a)在linux命令行下输入: ftp 192.168.1.1 b)服务器询问你用户名和密码 ...

  9. java中io流实现文件上传下载

    新建io.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" page ...

随机推荐

  1. swagger2常用注解说明

    说明: 1.这里使用的版本:springfox-swagger2(2.4)springfox-swagger-ui (2.4) 2.这里是说明常用注解的含义和基本用法(也就是说已经对swagger进行 ...

  2. Mac下Java JDK的下载安装和配置

    一.下载安装 打开一个搜索引擎,输入JDK,找到Java JDK 如图:  点击打开,同意协议开始下载如图: 下载好以后,安装即可. 安装成功以后,进入根目录,可以找到JDK安装的位置: 资源库——& ...

  3. HDU 1671 Phone List (qsort字符串排序与strncmp的使用 /字典树)

    Phone List Time Limit: 3000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total ...

  4. spring boot引入json,jsonobject,需要指定jdk15

    spring boot引入json,需要指定jdk15 <dependency> <groupId>net.sf.json-lib</groupId> <ar ...

  5. Django系列(一)

    项目引入静态文件 更改settings.py,为项目下面的每个APP应用,建立静态文件,这里如blog,首先在blog下面建立一个静态文件夹名为statics,注意这里为别名 STATICFILES_ ...

  6. DapperHelper 帮助类

    using System; using System.Collections.Generic; using System.Configuration; using System.Data; using ...

  7. Windows系统下安装运行Kafka

    一.安装JAVA JDK 1.下载安装包 http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151. ...

  8. MediatR

    1.MediatR是什么? 微软官方eshopOnContainer开源项目中使用到了该工具, mediatR 是一种中介工具,解耦了消息处理器和消息之间耦合的类库,支持跨平台 .net Standa ...

  9. jQuery滑动开关按钮效果

    效果图: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3 ...

  10. python全栈开发day62-两表操作增删改查,外键,if else模板语法

    一.今日内容总结: day62 内容回顾: 1. django有关所有命令: pip install django==1.11.14 django-admin startproject 项目名称 cd ...