java实现sftp客户端上传文件以及文件夹的功能代码
作者:java.小菜鸟 发布时间:2023-02-14 22:07:28
标签:java,上传
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 即可
来源:http://www.cnblogs.com/zuo-java/p/5913295.html


猜你喜欢
- 学会了Paint,Canvas的基本用法之后,我们就可以动手开始实践了,先写个简单的图片加载进度条看看。按照惯例,先看效果图,再决定要不要往
- 前言:我们每天都在编写Java代码,编译,执行。很多人已经知道Java源代码文件(.java后缀)会被Java编译器编译为字节码文件(.cl
- 定义与结构 备忘录(Memento)模式又称标记(Token)模式。GOF给备忘录模式的定义为:在不破坏
- 一,功能介绍本点单系统主要是基于SpringBoot框架和小程序开发的,主要是为当代人们的生活提供更便利、更高效的服务,也为营销者提供更好的
- java 二分法算法的实例1、前提:二分查找的前提是需要查找的数组必须是已排序的,我们这里的实现默认为升序2、原理:将数组分为三部分,依次是
- 序言:使用MyBatis3提供的注解可以逐步取代XML,例如使用@Select注解直接编写SQL完成数据查询,使用@SelectProvid
- 目录登陆界面的实现登陆界面代码Login类login的监听类 LoginListener聊天界面运行图Client类代码Server代码登陆
- 本文实例为大家分享了Android开发之自定义闹钟实现,供大家参考,具体内容如下闹钟时间设置及显示闹钟的布局很简单,就是一个简单时间设置,所
- 今天我来写一篇关于利用WPF来实现Windows的资源管理器功能,当然只是局部实现这个功能,因为在很多时候我们需要来实现对本机
- (1)不需要传递参数,也不需要返回参数ThreadStart是一个委托,这个委托的定义为void ThreadStart(),没有参数与返回
- 一、安装JDK、SDK、NDK无论是用C#和VS2015开发Androd App还是用Java和Eclipse开发Androd App,都需
- AndroidStudio打包jar最近更新androidstudio之后发现打包jar不可用了。先看下以前的方法更新后新的用法//Copy
- 枚举的定义1.题目枚举是JAVA 5.0后增加的一个重要类型。可以用来表示一组取值范围固定的变量。使用enum关键字,可以定义枚举类型。实现
- 目录首先,写一个需求文档:一、登录界面1.界面2.登录3.退出二、开始游戏界面三、缓冲加载游戏界面四、游戏主界面五、结束界面上代码首先,写一
- 周末这天手痒,正好没事干,想着写一个分页的例子出来给大家分享一下。这个案例分前端和后台两部分,前端使用面向对象的方式写的,里面用到了一些回调
- Java对称加密Cipher实现对称加密public class EncrypDES { // 字符串默认键值 &
- 题目:求1+2!+3!+...+20!的和程序分析:此程序只是把累加变成了累乘。程序设计:public class Ex21 {  
- 部分网友会发现Activity在切换到后台或布局从横屏LANDSCAPE切换到PORTRAIT,会重新切换Activity会触发一次onCr
- 需求是在我按下按钮时,该变按钮颜色,使用户感觉到自己按了按钮,当松开的时候,变回原来的颜色。正常时:按下时:有人说,直接监听按钮的按下事件不
- Netty设置为Https访问SSLContextFactorypublic class SSLContextFactory {