添加依赖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. 状态压缩dp小结

    最近一段时间算是学了一些状态压缩的题目,在这里做个小结吧 首先是炮兵布阵类题目,这类题目一开始给定一个矩形,要求在上面放置炮兵,如果在一格放了炮兵那么周围的某些格子就不能放炮兵,求最大能放置炮兵的数量 ...

  2. 用 DocumentFormat.OpenXml 和Microsoft.Office.Interop.Word 写入或者读取word文件

    using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Tex ...

  3. 设置IDEA中的web

  4. 解决bootstrap多模态框跳转时页面左移问题

    衍生问题暂未发现.... 忽略左右跳动视觉差 解决方法: 在bootstrap的js搜索padding-right,然后找到“+this.scrollbarWidth”,删掉即可.

  5. 读C#开发实战1200例子记录-2017年8月14日10:03:55

    C# 语言基础应用,注释 "///"标记不仅仅可以为代码段添加说明,它还有一项更重要的工作,就是用于生成自动文档.自动文档一般用于描述项目,是项目更加清晰直观.在VisualStu ...

  6. JAVA 数据类型数组

    普通int: public class Array { //成员变量 private int[] data; private int size; //构造函数,传入数组的容量capacity构造Arr ...

  7. exec函数族

    进程程序替换 进程程序替换原理 fork创建子进程执行的是和父进程相同的程序(也有可能是某个分支),通常fork出的子进程是为了完成父进程所分配的任务,所以子进程通常会调用一种exec函数(六种中的任 ...

  8. JavaBean toString() - 将bean对象打印成字符串

    JavaBean toString方式 https://www.cnblogs.com/thiaoqueen/p/7086195.html //方法一:自动生成 @Override public St ...

  9. Android补间动画、帧动画和属性动画使用知识介绍

    https://blog.csdn.net/zhangqunshuai/article/details/81098062

  10. T4模版自动生成MSSQL实体类

    在Model层建立ModelAuto.ttinclude文件 <#@ assembly name="System.Core"#> <#@ assembly nam ...