公司項目中需要把項目的相關文件上傳到服務器的tomcat中,需要在項目中進行以下幾步操作:
1.添加項目信息,包括名稱,描述,服務器ip,sftp的用戶名,密碼,端口號等,存在配置,部署,刪除等操作
2.配置:顯示出文件信息,包括文件路徑,目標路徑,類型(上傳,刪除),狀態(是否部署),
3.點擊部署時進行自動的部署,可以是文件上傳,也可以是相關文件的刪除
結合網上有關sftp完成的sftp工具類,只使用了多文件上傳和文件刪除功能,其他沒有進行測試,多文件上傳需要本地路徑和遠程路徑參數,文件夾刪除需要遠程路徑參數
1 package MyUtils; 2 3 import com.jcraft.jsch.*; 4 import org.apache.log4j.Logger; 5 6 import java.io.*; 7 import java.util.ArrayList; 8 import java.util.Iterator; 9 import java.util.List; 10 import java.util.Vector; 11 12 /** 13 * sftp工具類 14 * 15 16 */ 17 public class SFTPUtils { 18 private static Logger log = Logger.getLogger(SFTPUtils.class.getName()); 19 private static ChannelSftp sftp = null; 20 private static Session sshSession = null; 21 private static Integer i = 0; 22 23 24 /** 25 * 通過SFTP連接服務器 26 */ 27 public static void connect(String ip, String username, String password, Integer port) throws Exception { 28 29 JSch jsch = new JSch(); 30 try { 31 if (port <= 0) { 32 // 連接服務器,采用默認端口 33 sshSession = jsch.getSession(username, ip); 34 } else { 35 // 采用指定的端口連接服務器 36 sshSession = jsch.getSession(username, ip, port); 37 } 38 39 // 如果服務器連接不上,則拋出異常 40 if (sshSession == null) { 41 throw new Exception("服務器異常"); 42 } 43 44 // 設置登陸主機的密碼 45 sshSession.setPassword(password);// 設置密碼 46 // 設置第一次登陸的時候提示,可選值:(ask | yes | no) 47 sshSession.setConfig("StrictHostKeyChecking", "no"); 48 // 設置登陸超時時間 49 sshSession.connect(300000); 50 Channel channel = sshSession.openChannel("sftp"); 51 channel.connect(); 52 53 sftp = (ChannelSftp) channel; 54 55 } catch (Exception e) { 56 e.printStackTrace(); 57 throw e; 58 } 59 } 60 61 /** 62 * 關閉連接 63 */ 64 public static void disconnect() { 65 if (sftp != null) { 66 if (sftp.isConnected()) { 67 sftp.disconnect(); 68 if (log.isInfoEnabled()) { 69 log.info("已關閉sftp"); 70 } 71 } 72 } 73 if (sshSession != null) { 74 if (sshSession.isConnected()) { 75 sshSession.disconnect(); 76 if (log.isInfoEnabled()) { 77 log.info("已關閉sshSession"); 78 } 79 } 80 } 81 } 82 83 /** 84 * 批量下載文件 85 * 86 * @param remotePath:遠程下載目錄(以路徑符號結束) 87 * 88 * @param localPath:本地保存目錄(以路徑符號結束,D:\Duansha\sftp\) 89 * 90 * @param fileFormat:下載文件格式(以特定字符開頭,為空不做檢驗) 91 * 92 * @param fileEndFormat:下載文件格式(文件格式) 93 * @param del:下載后是否刪除sftp文件 94 * @return 95 */ 96 public List<String> batchDownLoadFile(String remotePath, String localPath, 97 String fileFormat, String fileEndFormat, boolean del) throws SftpException { 98 List<String> filenames = new ArrayList<String>(); 99 100 Vector v = sftp.ls(remotePath); 101 if (v.size() > 0) { 102 System.out.println("本次處理文件個數不為零,開始下載...fileSize=" + v.size()); 103 Iterator it = v.iterator(); 104 while (it.hasNext()) { 105 ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) it.next(); 106 String filename = entry.getFilename(); 107 SftpATTRS attrs = entry.getAttrs(); 108 if (!attrs.isDir()) { 109 boolean flag = false; 110 String localFileName = localPath + filename; 111 fileFormat = fileFormat == null ? "" : fileFormat 112 .trim(); 113 fileEndFormat = fileEndFormat == null ? "" 114 : fileEndFormat.trim(); 115 // 三種情況 116 if (fileFormat.length() > 0 && fileEndFormat.length() > 0) { 117 if (filename.startsWith(fileFormat) && filename.endsWith(fileEndFormat)) { 118 flag = downloadFile(remotePath, filename, localPath, filename); 119 if (flag) { 120 filenames.add(localFileName); 121 if (flag && del) { 122 deleteSFTP(remotePath); 123 } 124 } 125 } 126 } else if (fileFormat.length() > 0 && "".equals(fileEndFormat)) { 127 if (filename.startsWith(fileFormat)) { 128 flag = downloadFile(remotePath, filename, localPath, filename); 129 if (flag) { 130 filenames.add(localFileName); 131 if (flag && del) { 132 deleteSFTP(remotePath); 133 } 134 } 135 } 136 } else if (fileEndFormat.length() > 0 && "".equals(fileFormat)) { 137 if (filename.endsWith(fileEndFormat)) { 138 flag = downloadFile(remotePath, filename, localPath, filename); 139 if (flag) { 140 filenames.add(localFileName); 141 if (flag && del) { 142 deleteSFTP(remotePath); 143 } 144 } 145 } 146 } else { 147 flag = downloadFile(remotePath, filename, localPath, filename); 148 if (flag) { 149 filenames.add(localFileName); 150 if (flag && del) { 151 deleteSFTP(remotePath); 152 } 153 } 154 } 155 } 156 } 157 } 158 if (log.isInfoEnabled()) { 159 log.info("download file is success:remotePath=" + remotePath 160 + "and localPath=" + localPath + ",file size is" 161 + v.size()); 162 } 163 164 return filenames; 165 } 166 167 /** 168 * 下載單個文件 169 * 170 * @param remotePath:遠程下載目錄(以路徑符號結束)e 171 * @param remoteFileName:下載文件名 172 * @param localPath:本地保存目錄(以路徑符號結束) 173 * @param localFileName:保存文件名 174 * @return 175 */ 176 public boolean downloadFile(String remotePath, String remoteFileName, String localPath, String localFileName) { 177 FileOutputStream fieloutput = null; 178 try { 179 // sftp.cd(remotePath); 180 File file = new File(localPath + localFileName); 181 // mkdirs(localPath + localFileName); 182 fieloutput = new FileOutputStream(file); 183 sftp.get(remotePath + remoteFileName, fieloutput); 184 if (log.isInfoEnabled()) { 185 log.info("===DownloadFile:" + remoteFileName + " success from sftp."); 186 } 187 return true; 188 } catch (FileNotFoundException e) { 189 e.printStackTrace(); 190 } catch (SftpException e) { 191 e.printStackTrace(); 192 } finally { 193 if (null != fieloutput) { 194 try { 195 fieloutput.close(); 196 } catch (IOException e) { 197 e.printStackTrace(); 198 } 199 } 200 } 201 return false; 202 } 203 204 /** 205 * 上傳單個文件 206 * 207 * @param remotePath:遠程保存目錄 208 * @param localPath:本地上傳目錄(以路徑符號結束) 209 * @return 210 */ 211 public static void uploadFile(String remotePath, String localPath) throws Exception { 212 FileInputStream in = null; 213 File localFile = new File(localPath); 214 sftp.cd(remotePath); 215 in = new FileInputStream(localFile); 216 sftp.put(in, localFile.getName()); 217 218 if (in != null) { 219 in.close(); 220 } 221 } 222 223 /** 224 * 批量上傳文件 225 * 226 * @param remotePath:遠程保存目錄 227 * @param localPath:本地上傳目錄(以路徑符號結束) 228 * @return 229 */ 230 public static boolean bacthUploadFile(String remotePath, String localPath) throws Exception { 231 File localFile = new File(localPath); 232 boolean flag = true; 233 //進入遠程路徑 234 try { 235 if (!isDirExist(remotePath)) { 236 sftp.mkdir(remotePath); 237 sftp.cd(remotePath); 238 } else { 239 sftp.cd(remotePath); 240 } 241 //本地文件上傳 242 File file = new File(localPath); 243 //本地文件上傳方法 244 copyFile(file, sftp.pwd()); 245 246 247 } catch (Exception e) { 248 e.printStackTrace(); 249 flag = false; 250 throw e; 251 } 252 253 return flag; 254 } 255 256 private static void copyFile(File file, String pwd) throws Exception { 257 if (file.isDirectory()) { 258 File[] list = file.listFiles(); 259 String fileName = file.getName(); 260 sftp.cd(pwd); 261 System.out.println("正在創建目錄:" + sftp.pwd() + "/" + fileName); 262 sftp.mkdir(fileName); 263 System.out.println("目錄創建成功:" + sftp.pwd() + "/" + fileName); 264 //遠程路徑發生改變 265 pwd = pwd + "/" + file.getName(); 266 sftp.cd(file.getName()); 267 268 for (int i = 0; i < list.length; i++) { 269 copyFile(list[i], pwd); 270 } 271 } else { 272 //不是目錄,直接進入改變后的遠程路徑,進行上傳 273 sftp.cd(pwd); 274 275 System.out.println("正在復制文件:" + file.getAbsolutePath()); 276 InputStream instream = null; 277 OutputStream outstream = null; 278 outstream = sftp.put(file.getName()); 279 instream = new FileInputStream(file); 280 281 byte b[] = new byte[1024]; 282 int n; 283 while ((n = instream.read(b)) != -1) { 284 outstream.write(b, 0, n); 285 } 286 287 outstream.flush(); 288 outstream.close(); 289 instream.close(); 290 291 } 292 293 } 294 295 /** 296 * 刪除本地文件 297 * 298 * @param filePath 299 * @return 300 */ 301 public boolean deleteFile(String filePath) { 302 File file = new File(filePath); 303 if (!file.exists()) { 304 return false; 305 } 306 307 if (!file.isFile()) { 308 return false; 309 } 310 boolean rs = file.delete(); 311 if (rs && log.isInfoEnabled()) { 312 log.info("delete file success from local."); 313 } 314 return rs; 315 } 316 317 /** 318 * 創建目錄 319 * 320 * @param createpath 321 * @return 322 */ 323 public static void createDir(String createpath) { 324 try { 325 if (isDirExist(createpath)) { 326 sftp.cd(createpath); 327 } 328 String pathArry[] = createpath.split("/"); 329 StringBuffer filePath = new StringBuffer("/"); 330 for (String path : pathArry) { 331 if (path.equals("")) { 332 continue; 333 } 334 filePath.append(path + "/"); 335 if (isDirExist(filePath.toString())) { 336 sftp.cd(filePath.toString()); 337 } else { 338 // 建立目錄 339 sftp.mkdir(filePath.toString()); 340 // 進入並設置為當前目錄 341 sftp.cd(filePath.toString()); 342 } 343 344 } 345 } catch (SftpException e) { 346 e.printStackTrace(); 347 } 348 } 349 350 /** 351 * 判斷目錄是否存在 352 * 353 * @param directory 354 * @return 355 */ 356 public static boolean isDirExist(String directory) { 357 try { 358 Vector<?> vector = sftp.ls(directory); 359 if (null == vector) { 360 return false; 361 } else { 362 return true; 363 } 364 } catch (Exception e) { 365 return false; 366 } 367 } 368 369 /** 370 * 刪除stfp文件 371 * 372 * @param directory:要刪除文件所在目錄 373 */ 374 public static void deleteSFTP(String directory) { 375 try { 376 if (isDirExist(directory)) { 377 Vector<ChannelSftp.LsEntry> vector = sftp.ls(directory); 378 if (vector.size() == 1) { // 文件,直接刪除 379 sftp.rm(directory); 380 } else if (vector.size() == 2) { // 空文件夾,直接刪除 381 sftp.rmdir(directory); 382 } else { 383 String fileName = ""; 384 // 刪除文件夾下所有文件 385 for (ChannelSftp.LsEntry en : vector) { 386 fileName = en.getFilename(); 387 if (".".equals(fileName) || "..".equals(fileName)) { 388 continue; 389 } else { 390 deleteSFTP(directory + "/" + fileName); 391 } 392 } 393 // 刪除文件夾 394 sftp.rmdir(directory); 395 } 396 } 397 } catch (Exception e) { 398 e.printStackTrace(); 399 } 400 } 401 402 /** 403 * 如果目錄不存在就創建目錄 404 * 405 * @param path 406 */ 407 public void mkdirs(String path) { 408 File f = new File(path); 409 410 String fs = f.getParent(); 411 412 f = new File(fs); 413 414 if (!f.exists()) { 415 f.mkdirs(); 416 } 417 } 418 419 420 421 /** 422 * 測試 423 */ 424 public static void main(String[] args) { 425 // 本地存放地址 426 String localPath = "F:\\java\\src\\main\\webapp\\resources"; 427 // Sftp下載路徑 428 String sftpPath = "/home/sftp/"; 429 List<String> filePathList = new ArrayList<String>(); 430 try { 431 connect("111.16.123.12", "ftptest1", "123456", 22); 432 //deleteSFTP(sftpPath); 433 // 上傳 434 //bacthUploadFile(sftpPath, localPath); 435 //deleteSFTP("/home/ftp/ff"); 436 } catch (Exception e) { 437 e.printStackTrace(); 438 } finally { 439 sftp.disconnect(); 440 } 441 } 442 }