java实现sftp客户端上传文件以及文件夹的功能代码的详细介绍
本篇文章主要介绍了java实现sftp客户端上传文件以及文件夹的功能代码,具有一定的参考价值,有兴趣的可以了解一下。
1.依赖的jar文件 jsch-0.1.53.jar
2.登录方式有密码登录,和密匙登录
代码:
主函数:
import java.util.Properties; import com.cloudpower.util.Login; import com.util.LoadProperties; public class Ftp { public static void main(String[] args) { Properties properties = LoadProperties.getProperties(); Login.login(properties); } }
登陆页面的代码:
package com.cloudpower.util; import java.io.Console; import java.util.Properties; import com.jcraft.jsch.JSch; import com.jcraft.jsch.Session; public class Login { public static void login(Properties properties) { String ip = properties.getProperty("ip"); String user = properties.getProperty("user"); String pwd = properties.getProperty("pwd"); String port = properties.getProperty("port"); String privateKeyPath = properties.getProperty("privateKeyPath"); String passphrase = properties.getProperty("passphrase"); String sourcePath = properties.getProperty("sourcePath"); String destinationPath = properties.getProperty("destinationPath"); if (ip != null && !ip.equals("") && user != null && !user.equals("") && port != null && !port.equals("") && sourcePath != null && !sourcePath.equals("") && destinationPath != null && !destinationPath.equals("")) { if (privateKeyPath != null && !privateKeyPath.equals("")) { sshSftp2(ip, user, Integer.parseInt(port), privateKeyPath, passphrase, sourcePath, destinationPath); } else if (pwd != null && !pwd.equals("")) { sshSftp(ip, user, pwd, Integer.parseInt(port), sourcePath, destinationPath); } else { Console console = System.console(); System.out.print("Enter password:"); char[] readPassword = console.readPassword(); sshSftp(ip, user, new String(readPassword), Integer.parseInt(port), sourcePath, destinationPath); } } else { System.out.println("请先设置配置文件"); } } /** * 密码方式登录 * * @param ip * @param user * @param psw * @param port * @param sPath * @param dPath */ public static void sshSftp(String ip, String user, String psw, int port, String sPath, String dPath) { System.out.println("password login"); Session session = null; JSch jsch = new JSch(); try { if (port <= 0) { // 连接服务器,采用默认端口 session = jsch.getSession(user, ip); } else { // 采用指定的端口连接服务器 session = jsch.getSession(user, ip, port); } // 如果服务器连接不上,则抛出异常 if (session == null) { throw new Exception("session is null"); } // 设置登陆主机的密码 session.setPassword(psw);// 设置密码 // 设置第一次登陆的时候提示,可选值:(ask | yes | no) session.setConfig("StrictHostKeyChecking", "no"); // 设置登陆超时时间 session.connect(300000); UpLoadFile.upLoadFile(session, sPath, dPath); } catch (Exception e) { e.printStackTrace(); } System.out.println("success"); } /** * 密匙方式登录 * * @param ip * @param user * @param port * @param privateKey * @param passphrase * @param sPath * @param dPath */ public static void sshSftp2(String ip, String user, int port, String privateKey, String passphrase, String sPath, String dPath) { System.out.println("privateKey login"); Session session = null; JSch jsch = new JSch(); try { // 设置密钥和密码 // 支持密钥的方式登陆,只需在jsch.getSession之前设置一下密钥的相关信息就可以了 if (privateKey != null && !"".equals(privateKey)) { if (passphrase != null && "".equals(passphrase)) { // 设置带口令的密钥 jsch.addIdentity(privateKey, passphrase); } else { // 设置不带口令的密钥 jsch.addIdentity(privateKey); } } if (port <= 0) { // 连接服务器,采用默认端口 session = jsch.getSession(user, ip); } else { // 采用指定的端口连接服务器 session = jsch.getSession(user, ip, port); } // 如果服务器连接不上,则抛出异常 if (session == null) { throw new Exception("session is null"); } // 设置第一次登陆的时候提示,可选值:(ask | yes | no) session.setConfig("StrictHostKeyChecking", "no"); // 设置登陆超时时间 session.connect(300000); UpLoadFile.upLoadFile(session, sPath, dPath); System.out.println("success"); } catch (Exception e) { e.printStackTrace(); } } }
文件上传的代码:
package com.cloudpower.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Scanner; import com.jcraft.jsch.Channel; import com.jcraft.jsch.ChannelSftp; import com.jcraft.jsch.Session; import com.jcraft.jsch.SftpException; public class UpLoadFile { public static void upLoadFile(Session session, String sPath, String dPath) { Channel channel = null; try { channel = (Channel) session.openChannel("sftp"); channel.connect(10000000); ChannelSftp sftp = (ChannelSftp) channel; try { sftp.cd(dPath); Scanner scanner = new Scanner(System.in); System.out.println(dPath + ":此目录已存在,文件可能会被覆盖!是否继续y/n?"); String next = scanner.next(); if (!next.toLowerCase().equals("y")) { return; } } catch (SftpException e) { sftp.mkdir(dPath); sftp.cd(dPath); } File file = new File(sPath); copyFile(sftp, file, sftp.pwd()); } catch (Exception e) { e.printStackTrace(); } finally { session.disconnect(); channel.disconnect(); } } public static void copyFile(ChannelSftp sftp, File file, String pwd) { if (file.isDirectory()) { File[] list = file.listFiles(); try { try { String fileName = file.getName(); sftp.cd(pwd); System.out.println("正在创建目录:" + sftp.pwd() + "/" + fileName); sftp.mkdir(fileName); System.out.println("目录创建成功:" + sftp.pwd() + "/" + fileName); } catch (Exception e) { // TODO: handle exception } pwd = pwd + "/" + file.getName(); try { sftp.cd(file.getName()); } catch (SftpException e) { // TODO: handle exception e.printStackTrace(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } for (int i = 0; i < list.length; i++) { copyFile(sftp, list[i], pwd); } } else { try { sftp.cd(pwd); } catch (SftpException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("正在复制文件:" + file.getAbsolutePath()); InputStream instream = null; OutputStream outstream = null; try { outstream = sftp.put(file.getName()); instream = new FileInputStream(file); byte b[] = new byte[1024]; int n; try { while ((n = instream.read(b)) != -1) { outstream.write(b, 0, n); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (SftpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { outstream.flush(); outstream.close(); instream.close(); } catch (Exception e2) { // TODO: handle exception e2.printStackTrace(); } } } } }
读取配置文件的代码:
package com.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class LoadProperties { public static Properties getProperties() { File file = new File(Class.class.getClass().getResource("/").getPath() + "properties.properties"); InputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Properties properties = new Properties(); try { properties.load(inputStream); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return properties; } }
代码目录结构:
测试运行时配置文件放在项目的bin目录下(打包成可运行jar文件的时候要删除,打包完成后将配置文件和jar包放在同级目录下即可):
properties.properties
ip= user= pwd= port=22 privateKeyPath= passphrase= sourcePath= destinationPath=/home/dbbs/f
打包可运行jar文件:
Export->java->Runnabe JAR file
完成后
在控制台运行java -jar 导出jar包的名字.jar 即可
以上就是java实现sftp客户端上传文件以及文件夹的功能代码的详细介绍的内容,更多相关内容请关注PHP中文网(www.php.cn)!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Java 8引入了Stream API,提供了一种强大且表达力丰富的处理数据集合的方式。然而,使用Stream时,一个常见问题是:如何从forEach操作中中断或返回? 传统循环允许提前中断或返回,但Stream的forEach方法并不直接支持这种方式。本文将解释原因,并探讨在Stream处理系统中实现提前终止的替代方法。 延伸阅读: Java Stream API改进 理解Stream forEach forEach方法是一个终端操作,它对Stream中的每个元素执行一个操作。它的设计意图是处

胶囊是一种三维几何图形,由一个圆柱体和两端各一个半球体组成。胶囊的体积可以通过将圆柱体的体积和两端半球体的体积相加来计算。本教程将讨论如何使用不同的方法在Java中计算给定胶囊的体积。 胶囊体积公式 胶囊体积的公式如下: 胶囊体积 = 圆柱体体积 两个半球体体积 其中, r: 半球体的半径。 h: 圆柱体的高度(不包括半球体)。 例子 1 输入 半径 = 5 单位 高度 = 10 单位 输出 体积 = 1570.8 立方单位 解释 使用公式计算体积: 体积 = π × r2 × h (4

PHP是一种广泛应用于服务器端的脚本语言,特别适合web开发。1.PHP可以嵌入HTML,处理HTTP请求和响应,支持多种数据库。2.PHP用于生成动态网页内容,处理表单数据,访问数据库等,具有强大的社区支持和开源资源。3.PHP是解释型语言,执行过程包括词法分析、语法分析、编译和执行。4.PHP可以与MySQL结合用于用户注册系统等高级应用。5.调试PHP时,可使用error_reporting()和var_dump()等函数。6.优化PHP代码可通过缓存机制、优化数据库查询和使用内置函数。7

PHP和Python各有优势,选择应基于项目需求。1.PHP适合web开发,语法简单,执行效率高。2.Python适用于数据科学和机器学习,语法简洁,库丰富。

Java是热门编程语言,适合初学者和经验丰富的开发者学习。本教程从基础概念出发,逐步深入讲解高级主题。安装Java开发工具包后,可通过创建简单的“Hello,World!”程序实践编程。理解代码后,使用命令提示符编译并运行程序,控制台上将输出“Hello,World!”。学习Java开启了编程之旅,随着掌握程度加深,可创建更复杂的应用程序。
