SFTPUtil
1 package com.jf.utils; 2 3 import java.io.BufferedReader; 4 import java.io.ByteArrayInputStream; 5 import java.io.File; 6 import java.io.FileInputStream; 7 import java.io.FileOutputStream; 8 import java.io.IOException; 9 import java.io.InputStream; 10 import java.io.InputStreamReader; 11 import java.io.OutputStreamWriter; 12 import java.lang.reflect.Method; 13 import java.util.ArrayList; 14 import java.util.List; 15 import java.util.Properties; 16 import java.util.Vector; 17 18 import net.sf.json.JSON; 19 import net.sf.json.JSONObject; 20 import net.sf.json.xml.XMLSerializer; 21 22 import com.jcraft.jsch.Channel; 23 import com.jcraft.jsch.ChannelSftp; 24 import com.jcraft.jsch.JSch; 25 import com.jcraft.jsch.Session; 26 import com.jcraft.jsch.SftpException; 27 28 public class SftpUtils { 29 30 private static Session sshSession = null; 31 private static Channel channel = null; 32 private static ChannelSftp sftp = null; 33 34 private static String host = PropertiesUtils.getProperty("sip"); 35 private static int port = Integer.parseInt(PropertiesUtils.getProperty("sport")); 36 private static String userName = PropertiesUtils.getProperty("sUserName"); 37 private static String passWord = PropertiesUtils.getProperty("sPassWord"); 38 private static String localPath = PropertiesUtils.getProperty("localPath"); 39 public SftpUtils() { 40 } 41 42 /** 43 * 连接sftp服务器 44 * 45 * @param host 46 * 主机 47 * @param port 48 * 端口 49 * @param userName 50 * 用户名 51 * @param passWord 52 * 密码 53 */ 54 // static{ 55 // try { 56 // JSch jsch = new JSch(); 57 // jsch.getSession(userName, host, port); 58 // sshSession = jsch.getSession(userName, host, port); 59 // System.out.println("Session created."); 60 // sshSession.setPassword(passWord); 61 // Properties sshConfig = new Properties(); 62 // sshConfig.put("StrictHostKeyChecking", "no"); 63 // sshSession.setConfig(sshConfig); 64 // sshSession.connect(); 65 // System.out.println("Session connected."); 66 // channel = sshSession.openChannel("sftp"); 67 // channel.connect(); 68 // System.out.println("Opening Channel."); 69 // sftp = (ChannelSftp) channel; 70 // System.out.println("Connected to " + host + "."); 71 // } catch (Exception e) { 72 // 73 // } 74 // } 75 76 public static ChannelSftp getConnect() { 77 try { 78 JSch jsch = new JSch(); 79 jsch.getSession(userName, host, port); 80 sshSession = jsch.getSession(userName, host, port); 81 System.out.println("Session created."); 82 sshSession.setPassword(passWord); 83 Properties sshConfig = new Properties(); 84 sshConfig.put("StrictHostKeyChecking", "no"); 85 sshSession.setConfig(sshConfig); 86 sshSession.connect(); 87 System.out.println("Session connected."); 88 channel = sshSession.openChannel("sftp"); 89 channel.connect(); 90 System.out.println("Opening Channel."); 91 sftp = (ChannelSftp) channel; 92 System.out.println("Connected to " + host + "."); 93 } catch (Exception e) { 94 95 } 96 return sftp; 97 } 98 99 /** 100 * 上传文件 101 * 102 * @param directory 103 * 上传的目录 104 * @param uploadFile 105 * 要上传的文件 106 */ 107 public static void upload(String directory, String uploadFile) { 108 try { 109 sftp.cd(directory); 110 File file = new File(uploadFile); 111 sftp.put(new FileInputStream(file), file.getName()); 112 System.out.println("上传完成"); 113 } catch (Exception e) { 114 e.printStackTrace(); 115 } 116 } 117 118 /** 119 * 下载文件 120 * 121 * @param directory 122 * 下载目录 123 * @param downloadFile 124 * 下载的文件 125 * @param saveFile 126 * 存在本地的路径 127 */ 128 public static void download(String directory, String downloadFile,String saveFile) { 129 try { 130 sftp.cd(directory); 131 File file = new File(saveFile); 132 sftp.get(downloadFile, new FileOutputStream(file)); 133 System.out.println("下载完成"); 134 } catch (Exception e) { 135 e.printStackTrace(); 136 } 137 } 138 139 /** 140 * 删除文件 141 * 142 * @param directory 143 * 要删除文件所在目录 144 * @param deleteFile 145 * 要删除的文件 146 */ 147 public static void delete(String directory, String deleteFile) { 148 try { 149 sftp.cd(directory); 150 sftp.rm(deleteFile); 151 } catch (Exception e) { 152 e.printStackTrace(); 153 } 154 } 155 156 /** 157 * 列出目录下的文件 158 * 159 * @param directory 160 * 要列出的目录 161 * @return 162 * @throws SftpException 163 */ 164 @SuppressWarnings("rawtypes") 165 public static Vector listFiles(String directory) throws SftpException { 166 return sftp.ls(directory); 167 } 168 169 /** 关闭链接 */ 170 public static void close() { 171 if (sftp != null) { 172 sftp.quit(); 173 } 174 if (channel != null) { 175 channel.disconnect(); 176 } 177 if (sshSession != null) { 178 sshSession.disconnect(); 179 } 180 } 181 182 /** 183 * 上传流 184 * 185 * @param sInputString 186 * 要上传的字符串 187 * @param directory 188 * 上传的目录 189 * @param dst 190 * 目标文件名 191 */ 192 public static void upload(String sInputString, String directory, String dst) { 193 try { 194 sftp.cd(directory); 195 InputStream is = getStringStream(new String(sInputString.getBytes(), "GBK")); 196 sftp.put(is, dst); 197 System.out.println("上传完成"); 198 } catch (Exception e) { 199 e.printStackTrace(); 200 } 201 } 202 203 /** 204 * 将xml文件在本地创建 205 * @param xmlStr xml的内容 206 * @param fileName 文件名不带后缀 207 * @return 208 */ 209 public static String createXML(String xmlStr, String fileName) { 210 try { 211 File file = new File(localPath + fileName + ".xml"); 212 if(!file.getParentFile().exists()) 213 file.getParentFile().mkdirs(); 214 if (file.exists()) { 215 fileName = fileName + ((int) (Math.random() * (9999 - 1000 + 1)) + 1000); 216 file = new File(localPath + fileName + ".xml"); 217 } 218 file.createNewFile(); 219 FileOutputStream fos = new FileOutputStream(file); 220 OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); 221 osw.write(xmlStr.toCharArray()); 222 osw.flush(); 223 osw.close(); 224 } catch (Exception e) { 225 e.printStackTrace(); 226 } 227 return fileName + ".xml"; 228 } 229 230 /** 231 * 下载流 232 * 233 * @param directory 234 * 下载目录 235 * @param downloadFile 236 * 下载的文件 237 */ 238 public static String download(String directory, String downloadFile) { 239 try { 240 sftp.cd(directory); 241 InputStream is = sftp.get(downloadFile); 242 System.out.println("下载完成"); 243 return changeStreamToString(is); 244 } catch (Exception e) { 245 e.printStackTrace(); 246 return null; 247 } 248 } 249 250 /** 将字符串转化为InputStream流 */ 251 public static InputStream getStringStream(String sInputString) { 252 ByteArrayInputStream tInputStringStream = null; 253 try { 254 tInputStringStream = new ByteArrayInputStream(sInputString.getBytes()); 255 return tInputStringStream; 256 } catch (Exception ex) { 257 ex.printStackTrace(); 258 } finally { 259 try { 260 tInputStringStream.close(); 261 } catch (IOException e) { 262 e.printStackTrace(); 263 } 264 } 265 return null; 266 } 267 268 /** 将InputStream流转为String */ 269 public static String changeStreamToString(InputStream is) { 270 BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 271 StringBuilder sb = new StringBuilder(); 272 String line = null; 273 try { 274 while ((line = reader.readLine()) != null) { 275 sb.append(line + "\n"); 276 } 277 } catch (IOException e) { 278 e.printStackTrace(); 279 } finally { 280 try { 281 is.close(); 282 } catch (IOException e) { 283 e.printStackTrace(); 284 } 285 } 286 return sb.toString(); 287 } 288 289 /** 290 * 解析response——out文件夹下所有的文件存入list 291 * 292 * @throws Exception 293 */ 294 @SuppressWarnings("unused") 295 public static List<?> listenResponseFile() throws Exception { 296 String filePath = PropertiesUtils.getProperty("responseOut"); 297 List<?> list = new ArrayList<CdhResponse>(); 298 @SuppressWarnings("rawtypes") 299 Vector vector = listFiles(filePath); 300 if (0 < vector.size()) { 301 for (int i = 0; i < vector.size(); i++) { 302 // 当前文件的文件名 303 String fileName = getFieldValueByName("filename", vector.get(i)).toString(); 304 // 当前文件转换成JSONObject且全部为小写 305 JSONObject jsonObject = downLoadAndChangeToObject(filePath,fileName); 306 JSONObject headJson = JSONObject.fromObject(jsonObject.get("header")); 307 JSONObject bodyJson = JSONObject.fromObject(jsonObject.get("body")); 308 309 list.add(null); 310 } 311 } 312 return list; 313 } 314 315 /** 316 * 删除文件夹下所有文件 317 * 318 * @param filePath 319 */ 320 public static void deleteAllFiles(String filePath) { 321 try { 322 @SuppressWarnings("rawtypes") 323 Vector vector = listFiles(filePath); 324 for (int i = 0; i < vector.size(); i++) { 325 String fileName = getFieldValueByName("filename", vector.get(i)).toString(); 326 delete(filePath, fileName); 327 } 328 } catch (SftpException e) { 329 e.printStackTrace(); 330 } 331 } 332 333 334 /** 335 * 下载文件转换成JSONObject且全部为小写 336 * 337 * @param directory 338 * 下载目录 339 * @param downloadFile 340 * 下载的文件 341 */ 342 public static JSONObject downLoadAndChangeToObject(String directory,String downloadFile) throws Exception { 343 String str = SftpUtil.download(directory, downloadFile); 344 String[] str1 = str.split("<iframe"); 345 XMLSerializer xmlSerializer = new XMLSerializer(); 346 JSON json = xmlSerializer.read(str1[0]); 347 // 截取掉[],全部转为小写,转化为JSONObject 348 JSONObject jsonObject = JSONObject.fromObject(json.toString().toLowerCase().replace("[", "").replace("]", "")); 349 return jsonObject; 350 } 351 352 /** 通过属性名获取Object的属性值 */ 353 private static Object getFieldValueByName(String fieldName, Object o) { 354 try { 355 String firstLetter = fieldName.substring(0, 1).toUpperCase(); 356 String getter = "get" + firstLetter + fieldName.substring(1); 357 Method method = o.getClass().getMethod(getter, new Class[] {}); 358 Object value = method.invoke(o, new Object[] {}); 359 return value; 360 } catch (Exception e) { 361 return null; 362 } 363 } 364 365 public static void main(String[] args) { 366 /** 上传文件 */ 367 // SftpUtil.upload(directory, uploadFile); 368 /** 下载文件 */ 369 // SftpUtil.download("/REQUESTOUT/OUT", "TMS_xx.xml", 370 // "D:/tms/TMS_xxx.xml"); 371 /** 上传流 */ 372 // SftpUtil.upload(message(new SysOffice()).toString(), "/REQUESTIN/IN", 373 // "CREDIT_INPUT_cc.xml"); 374 375 // SftpUtil.close(); 376 377 /** 下载流并转为Object */ 378 // downLoadAndChangeToObject(); 379 380 System.out.println(createXML("xxx", "xx")); 381 } 382 383 }