java使用JSCH實現(xiàn)SFTP文件管理
本文實例為大家分享了java使用JSCH實現(xiàn)SFTP文件管理的具體代碼,供大家參考,具體內(nèi)容如下
一、連接配置
1.在項目中導(dǎo)入jsch-0.1.51.jar包;
2.創(chuàng)建SFTP類,存放連接屬性,其中要注意一點,在進行FTP操作時,一個會話在建立連接通道后進入A目錄進行文件操作,不能直接跳到同級或上級目錄操作,需要先退出當(dāng)前會話或者新建會話。
public class SFTP{
private Session session;//會話
private Channel channel;//連接通道
private ChannelSftp sftp;// sftp操作類
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public Channel getChannel() {
return channel;
}
public void setChannel(Channel channel) {
this.channel = channel;
}
public ChannelSftp getSftp() {
return sftp;
}
public void setSftp(ChannelSftp sftp) {
this.sftp = sftp;
}
}
3.創(chuàng)建SFTPUtil類,創(chuàng)建連接配置方法
/**
* 連接ftp/sftp服務(wù)器
* @param SFTP類
*/
public static void getConnect(SFTP s) throws Exception {
/** 密鑰的密碼 */
// String privateKey ="key";
// /** 密鑰文件路徑 */
// String passphrase ="path";
/** 主機 */
String host ="127.0.0.1";
/** 端口 */
int port =22;
/** 用戶名 */
String username ="test";
/** 密碼 */
String password ="test";
Session session = null;
Channel channel = null;
ChannelSftp sftp = null;// sftp操作類
JSch jsch = new JSch();
//設(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);
// }
// }
session = jsch.getSession(username, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no"); // 不驗證 HostKey
session.setConfig(config);
try {
session.connect();
} catch (Exception e) {
if (session.isConnected())
session.disconnect();
log.error("連接服務(wù)器失敗,請檢查主機[" + host + "],端口[" + port
+ "],用戶名[" + username + "],端口[" + port
+ "]是否正確,以上信息正確的情況下請檢查網(wǎng)絡(luò)連接是否正?;蛘哒埱蟊环阑饓芙^.");
}
channel = session.openChannel("sftp");
try {
channel.connect();
} catch (Exception e) {
if (channel.isConnected())
channel.disconnect();
log.error("連接服務(wù)器失敗,請檢查主機[" + host + "],端口[" + port
+ "],用戶名[" + username + "],密碼是否正確,以上信息正確的情況下請檢查網(wǎng)絡(luò)連接是否正?;蛘哒埱蟊环阑饓芙^.");
}
sftp = (ChannelSftp) channel;
s.setChannel(channel);
s.setSession(session);
s.setSftp(sftp);
}
5.關(guān)閉連接方法
/**
* 斷開連接
*
*/
public static void disConn(Session session,Channel channel,ChannelSftp sftp)throws Exception{
if(null != sftp){
sftp.disconnect();
sftp.exit();
sftp = null;
}
if(null != channel){
channel.disconnect();
channel = null;
}
if(null != session){
session.disconnect();
session = null;
}
}
二、SFTP目錄、文件操作管理
1.上傳文件
/**
* 上傳文件
* @param directory 上傳的目錄-相對于SFPT設(shè)置的用戶訪問目錄,
* 為空則在SFTP設(shè)置的根目錄進行創(chuàng)建文件(除設(shè)置了服務(wù)器全磁盤訪問)
* @param uploadFile 要上傳的文件全路徑
*/
public static void upload(String directory,String uploadFile) throws Exception {
SFTP s=new SFTP();
getConnect(s);//建立連接
Session session = s.getSession();
Channel channel = s.getChannel();
ChannelSftp sftp = s.getSftp();// sftp操作類
try {
try{
sftp.cd(directory); //進入目錄
}catch(SftpException sException){
if(sftp.SSH_FX_NO_SUCH_FILE == sException.id){ //指定上傳路徑不存在
sftp.mkdir(directory);//創(chuàng)建目錄
sftp.cd(directory); //進入目錄
}
}
}
File file = new File(uploadFile);
InputStream in= new FileInputStream(file);
sftp.put(in, file.getName());
in.close();
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
} finally {
disConn(session,channel,sftp);
}
}
2.文件下載
/**
* 下載文件
* @param directory 下載目錄 根據(jù)SFTP設(shè)置的根目錄來進行傳入
* @param downloadFile 下載的文件
* @param saveFile 存在本地的路徑
*/
public static void download(String directory, String downloadFile,String saveFile) throws Exception {
SFTP s=new SFTP();
getConnect(s);//建立連接
Session session = s.getSession();
Channel channel = s.getChannel();
ChannelSftp sftp = s.getSftp();// sftp操作類
try {
sftp.cd(directory); //進入目錄
File file = new File(saveFile);
boolean bFile;
bFile = false;
bFile = file.exists();
if (!bFile) {
bFile = file.mkdirs();//創(chuàng)建目錄
}
OutputStream out=new FileOutputStream(new File(saveFile,downloadFile));
sftp.get(downloadFile, out);
out.flush();
out.close();
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
} finally {
disConn(session,channel,sftp);
}
}
3.刪除文件
/**
* 刪除文件
* @param directory 要刪除文件所在目錄
* @param deleteFile 要刪除的文件
*/
public static void delete(String directory, String deleteFile) throws Exception {
SFTP s=new SFTP();
getConnect(s);//建立連接
Session session = s.getSession();
Channel channel = s.getChannel();
ChannelSftp sftp = s.getSftp();// sftp操作類
try {
sftp.cd(directory); //進入的目錄應(yīng)該是要刪除的目錄的上一級
sftp.rm(deleteFile);//刪除目錄
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
} finally {
disConn(session,channel,sftp);
}
}
4.列出目錄下的文件
/**
* 列出目錄下的文件
* @param directory 要列出的目錄
* @return list 文件名列表
* @throws Exception
*/
public static List<String> listFiles(String directory) throws Exception {
SFTP s=new SFTP();
getConnect(s);//建立連接
Session session = s.getSession();
Channel channel = s.getChannel();
ChannelSftp sftp = s.getSftp();// sftp操作類
Vector fileList=null;
List<String> fileNameList = new ArrayList<String>();
fileList = sftp.ls(directory); //返回目錄下所有文件名稱
disConn(session,channel,sftp);
Iterator it = fileList.iterator();
while(it.hasNext()) {
String fileName = ((LsEntry)it.next()).getFilename();
if(".".equals(fileName) || "..".equals(fileName)){
continue;
}
fileNameList.add(fileName);
}
return fileNameList;
}
5.刪除目錄下所有文件
/**
* 刪除目錄下所有文件
* @param directory 要刪除文件所在目錄
*/
public static void deleteAllFile(String directory) throws Exception{
SFTP s=new SFTP();
getConnect(s);//建立連接
Session session = s.getSession();
Channel channel = s.getChannel();
ChannelSftp sftp = s.getSftp();// sftp操作類
try {
List <String> files=listFiles(directory);//返回目錄下所有文件名稱
sftp.cd(directory); //進入目錄
for (String deleteFile : files) {
sftp.rm(deleteFile);//循環(huán)一次刪除目錄下的文件
}
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
} finally {
disConn(session,channel,sftp);
}
}
6.刪除目錄 (刪除的目錄必須為空)
/**
* 刪除目錄 (刪除的目錄必須為空)
* @param deleteDir 要刪除的目錄
*/
public static void deleteDir(String deleteDir) throws Exception {
SFTP s=new SFTP();
getConnect(s);//建立連接
Session session = s.getSession();
Channel channel = s.getChannel();
ChannelSftp sftp = s.getSftp();// sftp操作類
try {
sftp.rmdir(deleteDir);
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
} finally {
disConn(session,channel,sftp);
}
}
7.創(chuàng)建目錄
/**
* 創(chuàng)建目錄
* @param directory 要創(chuàng)建的目錄 位置
* @param dir 要創(chuàng)建的目錄
*/
public static void creatDir(String directory,String dir) throws Exception {
SFTP s=new SFTP();
getConnect(s);//建立連接
Session session = s.getSession();
Channel channel = s.getChannel();
ChannelSftp sftp = s.getSftp();// sftp操作類
try {
sftp.cd(directory);
sftp.mkdir(dir);
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
} finally {
disConn(session,channel,sftp);
}
}
8.更改文件名
/**
* 更改文件名
* @param directory 文件所在目錄
* @param oldFileNm 原文件名
* @param newFileNm 新文件名
* @throws Exception
*/
public static void rename(String directory, String oldFileNm, String newFileNm) throws Exception {
SFTP s=new SFTP();
getConnect(s);//建立連接
Session session = s.getSession();
Channel channel = s.getChannel();
ChannelSftp sftp = s.getSftp();// sftp操作類
try {
sftp.cd(directory);
sftp.rename(oldFileNm, newFileNm);
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
} finally {
disConn(session,channel,sftp);
}
}
9.進入目錄
/**
* 進入目錄
* @param directory
* @throws Exception
*/
public static void cd(String directory)throws Exception {
SFTP s=new SFTP();
getConnect(s);//建立連接
Session session = s.getSession();
Channel channel = s.getChannel();
ChannelSftp sftp = s.getSftp();// sftp操作類
try {
sftp.cd(directory); //目錄要一級一級進
} catch (Exception e) {
throw new Exception(e.getMessage(),e);
} finally {
disConn(session,channel,sftp);
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot中Elasticsearch的連接配置原理與使用詳解
Elasticsearch是一種開源的分布式搜索和數(shù)據(jù)分析引擎,它可用于全文搜索、結(jié)構(gòu)化搜索、分析等應(yīng)用場景,本文主要介紹了SpringBoot中Elasticsearch的連接配置原理與使用詳解,感興趣的可以了解一下2023-09-09
詳解spring cloud整合Swagger2構(gòu)建RESTful服務(wù)的APIs
這篇文章主要介紹了詳解spring cloud整合Swagger2構(gòu)建RESTful服務(wù)的APIs,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-01-01
spring boot使用自定義的線程池執(zhí)行Async任務(wù)
這篇文章主要介紹了spring boot使用自定義的線程池執(zhí)行Async任務(wù)的相關(guān)資料,需要的朋友可以參考下2018-02-02
使用IDEA搭建Hadoop開發(fā)環(huán)境的操作步驟(Window10為例)
經(jīng)過三次重裝,查閱無數(shù)資料后成功完成hadoop在win10上實現(xiàn)偽分布式集群,以及IDEA開發(fā)環(huán)境的搭建。一步一步跟著本文操作可以避免無數(shù)天坑2021-07-07
關(guān)于Spring注解@Async引發(fā)其他注解失效的解決
這篇文章主要介紹了關(guān)于Spring注解@Async引發(fā)其他注解失效的解決,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03
淺談Hibernate對象狀態(tài)之間的神奇轉(zhuǎn)換
這篇文章主要介紹了淺談Hibernate對象狀態(tài)之間的神奇轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
SpringBoot整合POI實現(xiàn)Excel文件讀寫操作
EasyExcel是一個基于Java的、快速、簡潔、解決大文件內(nèi)存溢出的Excel處理工具,這篇文章主要介紹了SpringBoot整合POI實現(xiàn)Excel文件讀寫操作,首先準備環(huán)境進行一系列操作,本文給大家介紹的非常詳細,需要的朋友參考下吧2023-10-10
Java面試題沖刺第十二天--數(shù)據(jù)庫(2)
這篇文章主要為大家分享了最有價值的三道數(shù)據(jù)庫面試題,涵蓋內(nèi)容全面,包括數(shù)據(jù)結(jié)構(gòu)和算法相關(guān)的題目、經(jīng)典面試編程題等,感興趣的小伙伴們可以參考一下2021-07-07

