添加依赖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. cf161d 求距离为k的点对(点分治,树形dp)

    点分治裸题,但是用树形dp也能做 /* dp[u][k]表示在u下距离k的点数量 */ #include<bits/stdc++.h> using namespace std; ]; ], ...

  2. C语言访问一个链接

    示例代码1: # include <Windows.h> int main(){ system("start http://""www.baidu.com&q ...

  3. Altium Designer (17.0) 打印输出指定的层

    Altium Designer (17.0) 例如,打印输出Top Overlay,Keep-Out Layer 1.先选择PCB文件,在单击按键Print Preview... 2.在预览区单击鼠标 ...

  4. du命令

    选项 例1:显示单个文件的大小(默认单位K) [root@zabbix alertscripts]# du -h sendim.py 4.0k sendim.py 例2:显示某个目录的总大小 例3:输 ...

  5. go-web项目性能测试,CPU, 内存泄露等

    go中提供了pprof包来做代码的性能监控,在两个地方有包: net/http/pprof runtime/pprof 其实net/http/pprof中只是使用runtime/pprof包来进行封装 ...

  6. .NET编码解码(HtmlEncode与HtmlDecode)

    编码代码: System.Web.HttpUtility.HtmlEncode("<a href=\"http://hovertree.com/\">何问起& ...

  7. [转] createObjectURL方法 实现本地图片预览

    ie6 可以直接显示本本地路径的图片 如: <img src="file://c:/3.jpg" />  ~~~网上都说ie7就不支持这种文件系统路径的url,但测试 ...

  8. javascript 语句和严格模式(三)

    一.语句 javascript程序由语句组成,语句遵守特定的语法规则. block break continue empty if...else switch try catch var functi ...

  9. 原 HTML5 requestFullScreen&exitFullscreen全屏兼容方案

                         摘要: html5 video全屏实现方式 首先来说,这个标题具有误导性,但这样设置改标题也是主要因为video使用的比较多 在html5中,全屏方法可以适用 ...

  10. 一起学Hive——详解四种导入数据的方式

    在使用Hive的过程中,导入数据是必不可少的步骤,不同的数据导入方式效率也不一样,本文总结Hive四种不同的数据导入方式: 从本地文件系统导入数据 从HDFS中导入数据 从其他的Hive表中导入数据 ...