java實(shí)現(xiàn)sftp客戶端上傳文件以及文件夾的功能代碼
1.依賴的jar文件 jsch-0.1.53.jar
2.登錄方式有密碼登錄,和密匙登錄
代碼:
主函數(shù):
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("請先設(shè)置配置文件");
}
}
/**
* 密碼方式登錄
*
* @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) {
// 連接服務(wù)器,采用默認(rèn)端口
session = jsch.getSession(user, ip);
} else {
// 采用指定的端口連接服務(wù)器
session = jsch.getSession(user, ip, port);
}
// 如果服務(wù)器連接不上,則拋出異常
if (session == null) {
throw new Exception("session is null");
}
// 設(shè)置登陸主機(jī)的密碼
session.setPassword(psw);// 設(shè)置密碼
// 設(shè)置第一次登陸的時候提示,可選值:(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
// 設(shè)置登陸超時時間
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 {
// 設(shè)置密鑰和密碼
// 支持密鑰的方式登陸,只需在jsch.getSession之前設(shè)置一下密鑰的相關(guān)信息就可以了
if (privateKey != null && !"".equals(privateKey)) {
if (passphrase != null && "".equals(passphrase)) {
// 設(shè)置帶口令的密鑰
jsch.addIdentity(privateKey, passphrase);
} else {
// 設(shè)置不帶口令的密鑰
jsch.addIdentity(privateKey);
}
}
if (port <= 0) {
// 連接服務(wù)器,采用默認(rèn)端口
session = jsch.getSession(user, ip);
} else {
// 采用指定的端口連接服務(wù)器
session = jsch.getSession(user, ip, port);
}
// 如果服務(wù)器連接不上,則拋出異常
if (session == null) {
throw new Exception("session is null");
}
// 設(shè)置第一次登陸的時候提示,可選值:(ask | yes | no)
session.setConfig("StrictHostKeyChecking", "no");
// 設(shè)置登陸超時時間
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 + ":此目錄已存在,文件可能會被覆蓋!是否繼續(xù)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("正在創(chuàng)建目錄:" + sftp.pwd() + "/" + fileName);
sftp.mkdir(fileName);
System.out.println("目錄創(chuàng)建成功:" + 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("正在復(fù)制文件:" + 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;
}
}
代碼目錄結(jié)構(gòu):

測試運(yùn)行時配置文件放在項(xiàng)目的bin目錄下(打包成可運(yùn)行jar文件的時候要刪除,打包完成后將配置文件和jar包放在同級目錄下即可):
properties.properties
ip= user= pwd= port=22 privateKeyPath= passphrase= sourcePath= destinationPath=/home/dbbs/f
打包可運(yùn)行jar文件:
Export->java->Runnabe JAR file
完成后
在控制臺運(yùn)行java -jar 導(dǎo)出jar包的名字.jar 即可
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用Java編寫導(dǎo)出不確定行數(shù)列數(shù)數(shù)據(jù)的工具類
這篇文章主要為大家詳細(xì)介紹了如何使用Java編寫導(dǎo)出不確定行數(shù)列數(shù)數(shù)據(jù)的工具類,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-03-03
基于Java的Socket編寫的C/S聊天程序?qū)崿F(xiàn)
這篇文章主要介紹了基于Java的Socket編寫的C/S聊天程序?qū)崿F(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-03-03
JavaFX 監(jiān)聽窗口關(guān)閉事件實(shí)例詳解
這篇文章主要介紹了JavaFX 監(jiān)聽窗口關(guān)閉事件實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下2017-05-05
SpringCloud服務(wù)接口調(diào)用OpenFeign及使用詳解
這篇文章主要介紹了SpringCloud服務(wù)接口調(diào)用——OpenFeign,在學(xué)習(xí)Ribbon時,服務(wù)間調(diào)用使用的是RestTemplate+Ribbon實(shí)現(xiàn),而Feign在此基礎(chǔ)上繼續(xù)進(jìn)行了封裝,使服務(wù)間調(diào)用變得更加方便,需要的朋友可以參考下2023-04-04
Java基于Graphics2D實(shí)現(xiàn)海報制作
這篇文章主要為大家詳細(xì)介紹了Java如何基于Graphics2D實(shí)現(xiàn)海報制作,并且支持自定義顏色,背景,logo,貼圖,感興趣的小伙伴可以了解一下2024-04-04

