最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
Java使用SFTP上传文件到服务器的简单使用
时间:2022-06-29 01:41:28 编辑:袖梨 来源:一聚教程网
| 代码如下 | 复制代码 |
/** * 将文件上传到服务器 * * @param filePath * 文件路径 * @param channelSftp * channelSftp对象 * @return */ publicstaticbooleanuploadFile(String filePath, ChannelSftp channelSftp) { OutputStream outstream =null; InputStream instream =null; booleansuccessFlag =false; try{ File isfile =newFile(filePath); if(isfile.isFile()) { outstream = channelSftp.put(isfile.getName()); File file =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(Exception e) { e.printStackTrace(); }finally{ try{ if(instream !=null) { instream.close(); } if(outstream !=null) { outstream.close(); } }catch(IOException e) { e.printStackTrace(); } } returnsuccessFlag; } privatestaticSession initJschSession() throwsJSchException { intftpPort =0; String ftpHost =""; String port ="00";//sftp的端口号 String ftpUserName ="";//用户名 String ftpPassword ="";//链接的密码 String privateKey ="";// String passphrase =""; if(port !=null&& !port.equals("")) { ftpPort = Integer.valueOf(port); } JSch jsch =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); Session session = jsch.getSession(ftpUserName, ftpHost, ftpPort);// 根据用户名,主机ip,端口获取一个Session对象 if(StringUtils.isNotBlank(ftpPassword)) { session.setPassword(ftpPassword);// 设置密码 } returnsession; } /** * 获取ChannelSftp链接 * * @param timeout * 超时时间 * @return 返回ChannelSftp对象 * @throws JSchException */ publicstaticChannelSftp getChannelSftp(Session session,inttimeout) throwsJSchException { Channel channel =null; Properties config =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链接 * * @param session * 会话 * @param channel * 通道 */ publicstaticvoidcloseConnection(Channel channel, Session session) { try{ if(session !=null) { session.disconnect();//关闭session链接 } if(channel !=null) { channel.disconnect();//断开连接 } }catch(Exception e) { e.printStackTrace(); } } | |
相关文章
- 啵乐腐味官方2026最新版-啵乐官方漫画网页版极速下载 02-06
- 一耽网页版登录入口怎么打开最新版本-2026可访问的一耽网页版登录入口免费安装 02-06
- 斗破苍穹漫画免费阅读入口:全章节高清无删减资源点此直达 02-06
- 差差漫画-官方页面登录 02-06
- 一耽原耽app官网最新版本下载入口-一耽漫画高清完整版资源在线观看 02-06
- 差差漫画-免费高清登录页面 02-06