操作ftp,直接在main方法中即可操作。
例1:遍歷ftp目錄中的文件
1 public static void main(String[] args) throws IOException { 2 3 FTPClient ftpClient = new FTPClient(); 4 5 try { 6 7 // 連接FTP服務器 8 ftpClient.connect("100.100.1.100", 21);//地址,端口號 9 10 // 登錄FTP服務器 11 ftpClient.login("admin", "admin");//用戶名,密碼 12 13 // 驗證FTP服務器是否登錄成功 14 ftpClient.setControlEncoding("UTF-8"); 15 16 int replyCode = ftpClient.getReplyCode(); 17 18 if (!FTPReply.isPositiveCompletion(replyCode)) { 19 System.out.println("登錄失敗"); 20 return; 21 }else{ 22 System.out.println("登錄成功"); 23 } 24 25 //根目錄 登錄到ftp后,所在的目錄即是根目錄,直接即可遍歷文件 26 FTPFile[] files = ftpClient.listFiles(); 27 for(FTPFile file: files){ 28 System.out.println(file.getName()); 29 } 30 31 // 切換目錄 想要遍歷那個目錄的文件,先要切換目錄(切換目錄實際就是進入目錄),進到目錄之后再進行遍歷 32 if(!ftpClient.changeWorkingDirectory("/transactionDetail")){ 33 System.out.println("切換目錄失敗"); 34 return; 35 }else{ 36 FTPFile[] fileDic = ftpClient.listFiles(); 37 for(FTPFile f: fileDic){ 38 System.out.println(f.getName()); 39 } 40 } 41 42 ftpClient.logout(); 43 44 } catch (IOException e) { 45 e.printStackTrace(); 46 } catch (Exception e) { 47 e.printStackTrace(); 48 } finally { 49 if (ftpClient.isConnected()) { 50 try { 51 ftpClient.logout(); 52 } catch (IOException e) { 53 54 } 55 } 56 } 57 }
例2:讀取(下載)ftp中的文件
1 public static void main(String[] args) throws IOException { 2 FTPClient ftpClient = new FTPClient(); 3 OutputStream out = null; 4 InputStream in = null; 5 try { 6 7 // 連接FTP服務器 8 ftpClient.connect("100.100.1.100", 21); 9 10 // 登錄FTP服務器 11 ftpClient.login("admin", "admin"); 12 13 // 驗證FTP服務器是否登錄成功 14 ftpClient.setControlEncoding("UTF-8"); 15 int replyCode = ftpClient.getReplyCode(); 16 17 if (!FTPReply.isPositiveCompletion(replyCode)) { 18 System.out.println("登錄失敗"); 19 }else{ 20 System.out.println("登錄成功"); 21 } 22 23 // 切換目錄 24 if(!ftpClient.changeWorkingDirectory("/book_detail")){ 25 System.out.println("切換目錄失敗"); 26 }else{ 27 in = new FileInputStream("detail-2020-02-20-xls.zip");//讀取目錄中的文件 28 //創建本地文件 29 File tmpFile = new File("D:" + File.separator + "route" + File.separator + "detail-2020-02-20-xls.zip"); 30 if (!tmpFile.getParentFile().exists()) { 31 tmpFile.getParentFile().mkdirs();//創建目錄 32 } 33 if(!tmpFile.exists()) { 34 tmpFile.createNewFile();//創建文件 35 } 36 out = new FileOutputStream(tmpFile); 37 38 // 創建字節數組 39 byte[] temp = new byte[1024]; 40 int length = 0; 41 42 // 源文件讀取一部分內容 43 while ((length = in.read(temp)) != -1) { 44 // 目標文件寫入一部分內容 45 out.write(temp, 0, length); 46 } 47 48 in.close(); 49 out.close(); 50 51 System.out.println("寫入本地成功"); 52 } 53 54 ftpClient.logout(); 55 } catch (IOException e) { 56 e.printStackTrace(); 57 } catch (Exception e) { 58 e.printStackTrace(); 59 } finally { 60 if (ftpClient.isConnected()) { 61 try { 62 ftpClient.logout(); 63 } catch (IOException e) { 64 65 } 66 } 67 } 68 }
所謂的下載實質上就是輸出。
