Java使用SFTP上传文件到服务器的简单使用
最近用到SFTP上传文件查找了一些资料后自己做了一点总结,方便以后的查询。具体代码如下所示:
/**
*将文件上传到服务器
*
*@paramfilePath
*文件路径
*@paramchannelSftp
*channelSftp对象
*@return
*/
publicstaticbooleanuploadFile(StringfilePath,ChannelSftpchannelSftp){
OutputStreamoutstream=null;
InputStreaminstream=null;
booleansuccessFlag=false;
try{
Fileisfile=newFile(filePath);
if(isfile.isFile()){
outstream=channelSftp.put(isfile.getName());
Filefile=newFile(filePath);
if(file.exists()){
instream=newFileInputStream(file);
byteb[]=newbyte[1024];
intn;
while((n=instream.read(b))!=-1){
outstream.write(b,0,n);
}
outstream.flush();
}
successFlag=true;
}
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
if(instream!=null){
instream.close();
}
if(outstream!=null){
outstream.close();
}
}catch(IOExceptione){
e.printStackTrace();
}
}
returnsuccessFlag;
}
privatestaticSessioninitJschSession()
throwsJSchException{
intftpPort=0;
StringftpHost="";
Stringport="00";//sftp的端口号
StringftpUserName="";//用户名
StringftpPassword="";//链接的密码
StringprivateKey="";//
Stringpassphrase="";
if(port!=null&&!port.equals("")){
ftpPort=Integer.valueOf(port);
}
JSchjsch=newJSch();//创建JSch对象
if(StringUtils.isNotBlank(privateKey)
&&StringUtils.isNotBlank(passphrase)){
jsch.addIdentity(privateKey,passphrase);
}
if(StringUtils.isNotBlank(privateKey)
&&StringUtils.isBlank(passphrase)){
jsch.addIdentity(privateKey);
}
jsch.getSession(ftpUserName,ftpHost,ftpPort);
Sessionsession=jsch.getSession(ftpUserName,ftpHost,ftpPort);//根据用户名,主机ip,端口获取一个Session对象
if(StringUtils.isNotBlank(ftpPassword)){
session.setPassword(ftpPassword);//设置密码
}
returnsession;
}
/**
*获取ChannelSftp链接
*
*@paramtimeout
*超时时间
*@return返回ChannelSftp对象
*@throwsJSchException
*/
publicstaticChannelSftpgetChannelSftp(Sessionsession,inttimeout)
throwsJSchException{
Channelchannel=null;
Propertiesconfig=newProperties();
config.put("StrictHostKeyChecking","no");
session.setConfig(config);//为Session对象设置properties
session.setTimeout(timeout);//设置timeout时间
session.connect();//通过Session建立链接
channel=session.openChannel("sftp");//打开SFTP通道
channel.connect();//建立SFTP通道的连接
return(ChannelSftp)channel;
}
/**
*断开sftp链接
*
*@paramsession
*会话
*@paramchannel
*通道
*/
publicstaticvoidcloseConnection(Channelchannel,Sessionsession){
try{
if(session!=null){
session.disconnect();//关闭session链接
}
if(channel!=null){
channel.disconnect();//断开连接
}
}catch(Exceptione){
e.printStackTrace();
}
}
这里的用户名密码都是自己设置,这里的方法进行了简单的封装,方便使用。
以上所述是小编给大家介绍的Java使用SFTP上传文件到服务器的简单使用,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!