java使用JSCH实现SFTP文件管理
本文实例为大家分享了java使用JSCH实现SFTP文件管理的具体代码,供大家参考,具体内容如下
一、连接配置
1.在项目中导入jsch-0.1.51.jar包;
2.创建SFTP类,存放连接属性,其中要注意一点,在进行FTP操作时,一个会话在建立连接通道后进入A目录进行文件操作,不能直接跳到同级或上级目录操作,需要先退出当前会话或者新建会话。
publicclassSFTP{
privateSessionsession;//会话
privateChannelchannel;//连接通道
privateChannelSftpsftp;//sftp操作类
publicSessiongetSession(){
returnsession;
}
publicvoidsetSession(Sessionsession){
this.session=session;
}
publicChannelgetChannel(){
returnchannel;
}
publicvoidsetChannel(Channelchannel){
this.channel=channel;
}
publicChannelSftpgetSftp(){
returnsftp;
}
publicvoidsetSftp(ChannelSftpsftp){
this.sftp=sftp;
}
}
3.创建SFTPUtil类,创建连接配置方法
/**
*连接ftp/sftp服务器
*@paramSFTP类
*/
publicstaticvoidgetConnect(SFTPs)throwsException{
/**密钥的密码*/
//StringprivateKey="key";
///**密钥文件路径*/
//Stringpassphrase="path";
/**主机*/
Stringhost="127.0.0.1";
/**端口*/
intport=22;
/**用户名*/
Stringusername="test";
/**密码*/
Stringpassword="test";
Sessionsession=null;
Channelchannel=null;
ChannelSftpsftp=null;//sftp操作类
JSchjsch=newJSch();
//设置密钥和密码
//支持密钥的方式登陆,只需在jsch.getSession之前设置一下密钥的相关信息就可以了
//if(privateKey!=null&&!"".equals(privateKey)){
//if(passphrase!=null&&"".equals(passphrase)){
////设置带口令的密钥
//jsch.addIdentity(privateKey,passphrase);
//}else{
////设置不带口令的密钥
//jsch.addIdentity(privateKey);
//}
//}
session=jsch.getSession(username,host,port);
session.setPassword(password);
Propertiesconfig=newProperties();
config.put("StrictHostKeyChecking","no");//不验证HostKey
session.setConfig(config);
try{
session.connect();
}catch(Exceptione){
if(session.isConnected())
session.disconnect();
log.error("连接服务器失败,请检查主机["+host+"],端口["+port
+"],用户名["+username+"],端口["+port
+"]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
}
channel=session.openChannel("sftp");
try{
channel.connect();
}catch(Exceptione){
if(channel.isConnected())
channel.disconnect();
log.error("连接服务器失败,请检查主机["+host+"],端口["+port
+"],用户名["+username+"],密码是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
}
sftp=(ChannelSftp)channel;
s.setChannel(channel);
s.setSession(session);
s.setSftp(sftp);
}
5.关闭连接方法
/**
*断开连接
*
*/
publicstaticvoiddisConn(Sessionsession,Channelchannel,ChannelSftpsftp)throwsException{
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.上传文件
/**
*上传文件
*@paramdirectory上传的目录-相对于SFPT设置的用户访问目录,
*为空则在SFTP设置的根目录进行创建文件(除设置了服务器全磁盘访问)
*@paramuploadFile要上传的文件全路径
*/
publicstaticvoidupload(Stringdirectory,StringuploadFile)throwsException{
SFTPs=newSFTP();
getConnect(s);//建立连接
Sessionsession=s.getSession();
Channelchannel=s.getChannel();
ChannelSftpsftp=s.getSftp();//sftp操作类
try{
try{
sftp.cd(directory);//进入目录
}catch(SftpExceptionsException){
if(sftp.SSH_FX_NO_SUCH_FILE==sException.id){//指定上传路径不存在
sftp.mkdir(directory);//创建目录
sftp.cd(directory);//进入目录
}
}
}
Filefile=newFile(uploadFile);
InputStreamin=newFileInputStream(file);
sftp.put(in,file.getName());
in.close();
}catch(Exceptione){
thrownewException(e.getMessage(),e);
}finally{
disConn(session,channel,sftp);
}
}
2.文件下载
/**
*下载文件
*@paramdirectory下载目录根据SFTP设置的根目录来进行传入
*@paramdownloadFile下载的文件
*@paramsaveFile存在本地的路径
*/
publicstaticvoiddownload(Stringdirectory,StringdownloadFile,StringsaveFile)throwsException{
SFTPs=newSFTP();
getConnect(s);//建立连接
Sessionsession=s.getSession();
Channelchannel=s.getChannel();
ChannelSftpsftp=s.getSftp();//sftp操作类
try{
sftp.cd(directory);//进入目录
Filefile=newFile(saveFile);
booleanbFile;
bFile=false;
bFile=file.exists();
if(!bFile){
bFile=file.mkdirs();//创建目录
}
OutputStreamout=newFileOutputStream(newFile(saveFile,downloadFile));
sftp.get(downloadFile,out);
out.flush();
out.close();
}catch(Exceptione){
thrownewException(e.getMessage(),e);
}finally{
disConn(session,channel,sftp);
}
}
3.删除文件
/**
*删除文件
*@paramdirectory要删除文件所在目录
*@paramdeleteFile要删除的文件
*/
publicstaticvoiddelete(Stringdirectory,StringdeleteFile)throwsException{
SFTPs=newSFTP();
getConnect(s);//建立连接
Sessionsession=s.getSession();
Channelchannel=s.getChannel();
ChannelSftpsftp=s.getSftp();//sftp操作类
try{
sftp.cd(directory);//进入的目录应该是要删除的目录的上一级
sftp.rm(deleteFile);//删除目录
}catch(Exceptione){
thrownewException(e.getMessage(),e);
}finally{
disConn(session,channel,sftp);
}
}
4.列出目录下的文件
/** *列出目录下的文件 *@paramdirectory要列出的目录 *@returnlist文件名列表 *@throwsException */ publicstaticListlistFiles(Stringdirectory)throwsException{ SFTPs=newSFTP(); getConnect(s);//建立连接 Sessionsession=s.getSession(); Channelchannel=s.getChannel(); ChannelSftpsftp=s.getSftp();//sftp操作类 VectorfileList=null; List fileNameList=newArrayList (); fileList=sftp.ls(directory);//返回目录下所有文件名称 disConn(session,channel,sftp); Iteratorit=fileList.iterator(); while(it.hasNext()){ StringfileName=((LsEntry)it.next()).getFilename(); if(".".equals(fileName)||"..".equals(fileName)){ continue; } fileNameList.add(fileName); } returnfileNameList; }
5.删除目录下所有文件
/**
*删除目录下所有文件
*@paramdirectory要删除文件所在目录
*/
publicstaticvoiddeleteAllFile(Stringdirectory)throwsException{
SFTPs=newSFTP();
getConnect(s);//建立连接
Sessionsession=s.getSession();
Channelchannel=s.getChannel();
ChannelSftpsftp=s.getSftp();//sftp操作类
try{
Listfiles=listFiles(directory);//返回目录下所有文件名称
sftp.cd(directory);//进入目录
for(StringdeleteFile:files){
sftp.rm(deleteFile);//循环一次删除目录下的文件
}
}catch(Exceptione){
thrownewException(e.getMessage(),e);
}finally{
disConn(session,channel,sftp);
}
}
6.删除目录(删除的目录必须为空)
/**
*删除目录(删除的目录必须为空)
*@paramdeleteDir要删除的目录
*/
publicstaticvoiddeleteDir(StringdeleteDir)throwsException{
SFTPs=newSFTP();
getConnect(s);//建立连接
Sessionsession=s.getSession();
Channelchannel=s.getChannel();
ChannelSftpsftp=s.getSftp();//sftp操作类
try{
sftp.rmdir(deleteDir);
}catch(Exceptione){
thrownewException(e.getMessage(),e);
}finally{
disConn(session,channel,sftp);
}
}
7.创建目录
/**
*创建目录
*@paramdirectory要创建的目录位置
*@paramdir要创建的目录
*/
publicstaticvoidcreatDir(Stringdirectory,Stringdir)throwsException{
SFTPs=newSFTP();
getConnect(s);//建立连接
Sessionsession=s.getSession();
Channelchannel=s.getChannel();
ChannelSftpsftp=s.getSftp();//sftp操作类
try{
sftp.cd(directory);
sftp.mkdir(dir);
}catch(Exceptione){
thrownewException(e.getMessage(),e);
}finally{
disConn(session,channel,sftp);
}
}
8.更改文件名
/**
*更改文件名
*@paramdirectory文件所在目录
*@paramoldFileNm原文件名
*@paramnewFileNm新文件名
*@throwsException
*/
publicstaticvoidrename(Stringdirectory,StringoldFileNm,StringnewFileNm)throwsException{
SFTPs=newSFTP();
getConnect(s);//建立连接
Sessionsession=s.getSession();
Channelchannel=s.getChannel();
ChannelSftpsftp=s.getSftp();//sftp操作类
try{
sftp.cd(directory);
sftp.rename(oldFileNm,newFileNm);
}catch(Exceptione){
thrownewException(e.getMessage(),e);
}finally{
disConn(session,channel,sftp);
}
}
9.进入目录
/**
*进入目录
*@paramdirectory
*@throwsException
*/
publicstaticvoidcd(Stringdirectory)throwsException{
SFTPs=newSFTP();
getConnect(s);//建立连接
Sessionsession=s.getSession();
Channelchannel=s.getChannel();
ChannelSftpsftp=s.getSftp();//sftp操作类
try{
sftp.cd(directory);//目录要一级一级进
}catch(Exceptione){
thrownewException(e.getMessage(),e);
}finally{
disConn(session,channel,sftp);
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。