java sftp jar_java SFTP工具类

1 importjava.io.File;2 importjava.io.FileInputStream;3 importjava.io.FileOutputStream;4 importjava.io.IOException;5 importjava.io.InputStream;6 importjava.util.ArrayList;7 importjava.util.Iterator;8 importjava.util.List;9 importjava.util.Properties;10 importjava.util.Vector;11

12 importcom.jcraft.jsch.Channel;13 importcom.jcraft.jsch.ChannelSftp;14 importcom.jcraft.jsch.ChannelSftp.LsEntry;15 importcom.jcraft.jsch.JSch;16 importcom.jcraft.jsch.JSchException;17 importcom.jcraft.jsch.Session;18 importcom.jcraft.jsch.SftpException;19

20 /**

21 * 提供SFTP处理文件服务22 *23 *@authorkrm-hehongtao24 * @date 2016-02-2925 *26 */

27 public classSFTPUtil {28 private JSch jSch = null;29 private ChannelSftp sftp = null;//sftp主服务

30 private Channel channel = null;31 private Session session = null;32

33 private String hostName = "192.168.0.177";//远程服务器地址

34 private int port = 22;//端口

35 private String userName = "weblogic";//用户名

36 private String password = "weblogic";//密码

37

38 public SFTPUtil(String hostName, intport, String userName, String password) {39 this.hostName =hostName;40 this.port =port;41 this.userName =userName;42 this.password =password;43 }44

45 /**

46 * 连接登陆远程服务器47 *48 *@return

49 */

50 public boolean connect() throwsException {51 try{52 jSch = newJSch();53 session =jSch.getSession(userName, hostName, port);54 session.setPassword(password);55

56 session.setConfig(this.getSshConfig());57 session.connect();58

59 channel = session.openChannel("sftp");60 channel.connect();61

62 sftp =(ChannelSftp) channel;63 System.out.println("登陆成功:" +sftp.getServerVersion());64

65 } catch(JSchException e) {66 System.err.println("SSH方式连接FTP服务器时有JSchException异常!");67 System.err.println(e.getMessage());68 throwe;69 }70 return true;71 }72

73 /**

74 * 关闭连接75 *76 *@throwsException77 */

78 private void disconnect() throwsException {79 try{80 if(sftp.isConnected()) {81 sftp.disconnect();82 }83 if(channel.isConnected()) {84 channel.disconnect();85 }86 if(session.isConnected()) {87 session.disconnect();88 }89 } catch(Exception e) {90 throwe;91 }92 }93

94 /**

95 * 获取服务配置96 *97 *@return

98 */

99 private Properties getSshConfig() throwsException {100 Properties sshConfig = null;101 try{102 sshConfig = newProperties();103 sshConfig.put("StrictHostKeyChecking", "no");104

105 } catch(Exception e) {106 throwe;107 }108 returnsshConfig;109 }110

111 /**

112 * 下载远程sftp服务器文件113 *114 *@paramremotePath115 *@paramremoteFilename116 *@paramlocalFilename117 *@return

118 */

119 public booleandownloadFile(String remotePath, String remoteFilename, String localFilename)120 throwsSftpException, IOException, Exception {121 FileOutputStream output = null;122 boolean success = false;123 try{124 if (null != remotePath && remotePath.trim() != "") {125 sftp.cd(remotePath);126 }127

128 File localFile = newFile(localFilename);129 //有文件和下载文件重名

130 if(localFile.exists()) {131 System.err.println("文件: " + localFilename + " 已经存在!");132 returnsuccess;133 }134 output = newFileOutputStream(localFile);135 sftp.get(remoteFilename, output);136 success = true;137 System.out.println("成功接收文件,本地路径:" +localFilename);138 } catch(SftpException e) {139 System.err.println("接收文件时有SftpException异常!");140 System.err.println(e.getMessage());141 returnsuccess;142 } catch(IOException e) {143 System.err.println("接收文件时有I/O异常!");144 System.err.println(e.getMessage());145 returnsuccess;146 } finally{147 try{148 if (null !=output) {149 output.close();150 }151 //关闭连接

152 disconnect();153 } catch(IOException e) {154 System.err.println("关闭文件时出错!");155 System.err.println(e.getMessage());156 }157 }158 returnsuccess;159 }160

161 /**

162 * 上传文件至远程sftp服务器163 *164 *@paramremotePath165 *@paramremoteFilename166 *@paramlocalFileName167 *@return

168 */

169 public booleanuploadFile(String remotePath, String remoteFilename, String localFileName)170 throwsSftpException, Exception {171 boolean success = false;172 FileInputStream fis = null;173 try{174 //更改服务器目录

175 if (null != remotePath && remotePath.trim() != "") {176 sftp.cd(remotePath);177 }178 File localFile = newFile(localFileName);179 fis = newFileInputStream(localFile);180 //发送文件

181 sftp.put(fis, remoteFilename);182 success = true;183 System.out.println("成功发送文件,本地路径:" +localFileName);184 } catch(SftpException e) {185 System.err.println("发送文件时有SftpException异常!");186 e.printStackTrace();187 System.err.println(e.getMessage());188 throwe;189 } catch(Exception e) {190 System.err.println("发送文件时有异常!");191 System.err.println(e.getMessage());192 throwe;193 } finally{194 try{195 if (null !=fis) {196 fis.close();197 }198 //关闭连接

199 disconnect();200 } catch(IOException e) {201 System.err.println("关闭文件时出错!");202 System.err.println(e.getMessage());203 }204 }205 returnsuccess;206 }207

208 /**

209 * 上传文件至远程sftp服务器210 *211 *@paramremotePath212 *@paramremoteFilename213 *@paraminput214 *@return

215 */

216 public booleanuploadFile(String remotePath, String remoteFilename, InputStream input)217 throwsSftpException, Exception {218 boolean success = false;219 try{220 //更改服务器目录

221 if (null != remotePath && remotePath.trim() != "") {222 sftp.cd(remotePath);223 }224

225 //发送文件

226 sftp.put(input, remoteFilename);227 success = true;228 } catch(SftpException e) {229 System.err.println("发送文件时有SftpException异常!");230 e.printStackTrace();231 System.err.println(e.getMessage());232 throwe;233 } catch(Exception e) {234 System.err.println("发送文件时有异常!");235 System.err.println(e.getMessage());236 throwe;237 } finally{238 try{239 if (null !=input) {240 input.close();241 }242 //关闭连接

243 disconnect();244 } catch(IOException e) {245 System.err.println("关闭文件时出错!");246 System.err.println(e.getMessage());247 }248

249 }250 returnsuccess;251 }252

253 /**

254 * 删除远程文件255 *256 *@paramremotePath257 *@paramremoteFilename258 *@return

259 *@throwsException260 */

261 public boolean deleteFile(String remotePath, String remoteFilename) throwsException {262 boolean success = false;263 try{264 //更改服务器目录

265 if (null != remotePath && remotePath.trim() != "") {266 sftp.cd(remotePath);267 }268

269 //删除文件

270 sftp.rm(remoteFilename);271 System.err.println("删除远程文件" + remoteFilename + "成功!");272 success = true;273 } catch(SftpException e) {274 System.err.println("删除文件时有SftpException异常!");275 e.printStackTrace();276 System.err.println(e.getMessage());277 returnsuccess;278 } catch(Exception e) {279 System.err.println("删除文件时有异常!");280 System.err.println(e.getMessage());281 returnsuccess;282 } finally{283 //关闭连接

284 disconnect();285 }286 returnsuccess;287 }288

289 /**

290 * 遍历远程文件291 *292 *@paramremotePath293 *@return

294 *@throwsException295 */

296 public List listFiles(String remotePath) throwsSftpException {297 List ftpFileNameList = new ArrayList();298 Vector sftpFile =sftp.ls(remotePath);299 LsEntry isEntity = null;300 String fileName = null;301 Iterator sftpFileNames =sftpFile.iterator();302 while(sftpFileNames.hasNext()) {303 isEntity =(LsEntry) sftpFileNames.next();304 fileName =isEntity.getFilename();305 System.out.println(fileName);306 ftpFileNameList.add(fileName);307 }308 returnftpFileNameList;309 }310

311 /**

312 * 判断路径是否存在313 *314 *@paramremotePath315 *@return

316 *@throwsSftpException317 */

318 public boolean isExist(String remotePath) throwsSftpException {319 boolean flag = false;320 try{321 sftp.cd(remotePath);322 System.out.println("存在路径:" +remotePath);323 flag = true;324 } catch(SftpException sException) {325

326 } catch(Exception Exception) {327 }328 returnflag;329 }330

331 publicString getHostName() {332 returnhostName;333 }334

335 public voidsetHostName(String hostName) {336 this.hostName =hostName;337 }338

339 public intgetPort() {340 returnport;341 }342

343 public void setPort(intport) {344 this.port =port;345 }346

347 publicString getUserName() {348 returnuserName;349 }350

351 public voidsetUserName(String userName) {352 this.userName =userName;353 }354

355 publicString getPassword() {356 returnpassword;357 }358

359 public voidsetPassword(String password) {360 this.password =password;361 }362

363 /**

364 * 测试方法365 *366 */

367 public static voidmain(String[] args) {368 try{369 SFTPUtil sftp = new SFTPUtil("192.168.0.177", 22, "weblogic", "weblogic");370 System.out.println(new StringBuffer().append(" 服务器地址: ")371 .append(sftp.getHostName()).append(" 端口:").append(sftp.getPort())372 .append("用户名:").append(sftp.getUserName()).append("密码:")373 .append(sftp.getPassword().toString()));374 sftp.connect();375 if (sftp.isExist("/home/weblogic/project")) {376 sftp.listFiles("/home/weblogic/project");377 sftp.downloadFile("/home/weblogic/project", "S123456_20150126.csv",378 "D:\\S123456_20150126.csv");379 //sftp.uploadFile("\\", "test.txt", "D:\\work\\readMe.txt");380 //sftp.deleteFile("\\", "test.txt");

381 }382 } catch(Exception e) {383 System.out.println("异常信息:" +e.getMessage());384 }385 }386 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值