ftp上傳下載文件詳解

首先導入包

import org.apache.commons.NET.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

FTPClient類庫主要提供了用於建立FTP連接的類。利用這些類的方法,編程人員可以遠程登錄到FTP服務器,列舉該服務器上的目錄,設置傳輸協議,以及傳送文件。FtpClient類涵蓋了幾乎所有FTP的功能,FtpClient的實例變量保存了有關建立”代理”的各種信息。下面給出了這些實例變量。

public static boolean useFtpProxy

  這個變量用於表明FTP傳輸過程中是否使用了一個代理,因此,它實際上是一個標記,此標記若爲TRUE,表明使用了一個代理主機。

  public static String ftpProxyHost

  此變量只有在變量useFtpProxy爲TRUE時纔有效,用於保存代理主機名。

  public static int ftpProxyPort

  此變量只有在變量useFtpProxy爲TRUE時纔有效,用於保存代理主機的端口地址。

FtpClient有三種不同形式的構造函數,如下所示:

  1、public FtpClient(String hostname,int port)

   此構造函數利用給出的主機名和端口號建立一條FTP連接。

  2、public FtpClient(String hostname)

  此構造函數利用給出的主機名建立一條FTP連接,使用默認端口號。

  3、FtpClient()

  此構造函數將創建一FtpClient類,但不建立FTP連接。這時,FTP連接可以用openServer方法建立。

  一旦建立了類FtpClient,就可以用這個類的方法來打開與FTP服務器的連接。類ftpClient提供瞭如下兩個可用於打開與FTP服務器之間的連接的方法。

public void openServer(String hostname)

  這個方法用於建立一條與指定主機上的FTP服務器的連接,使用默認端口號。

  public void openServer(String host,int port)

  這個方法用於建立一條與指定主機、指定端口上的FTP服務器的連接。

  打開連接之後,接下來的工作是註冊到FTP服務器。這時需要利用下面的方法。

  public void login(String username,String password)

  此方法利用參數username和password登錄到FTP服務器。使用過Intemet的用戶應該知道,匿名FTP服務器的登錄用戶名爲anonymous,密碼一般用自己的電子郵件地址。


下面是FtpClient類所提供的一些控制命令。

  public void cd(String remoteDirectory)

  該命令用於把遠程系統上的目錄切換到參數remoteDirectory所指定的目錄。

  public void cdUp():該命令用於把遠程系統上的目錄切換到上一級目錄。

  public String pwd():該命令可顯示遠程系統上的目錄狀態。

  public void binary():該命令可把傳輸格式設置爲二進制格式。

  public void ascii():該命令可把傳輸協議設置爲ASCII碼格式。

  public void rename(String string,String string1)

  該命令可對遠程系統上的目錄或者文件進行重命名操作。

  除了上述方法外,類FtpClient還提供了可用於傳遞並檢索目錄清單和文件的若干方法。這些方法返回的是可供讀或寫的輸入、輸出流。下面是其中一些主要的方法。

public TelnetInputStream list()

  返回與遠程機器上當前目錄相對應的輸入流。

  public TelnetInputStream get(String filename)

  獲取遠程機器上的文件filename,藉助TelnetInputStream把該文件傳送到本地。

  public TelnetOutputStream put(String filename)

  以寫方式打開一輸出流,通過這一輸出流把文件filename傳送到遠程計算機。

案例:

      public FTPClient ftp = new FTPClient(); // 實例化ftp客戶端對象。

      /*******************登陸***********************/

     // 開始讀取 就去連接FTP服務器
    if (ftp.isConnected() == false) 
    {
     try 
     {
      ftp.connect(host_ip);// 連接 Ftp  host_ip FTP服務器ip
      try 
      {
       ftp.login(username, password);// 登陸  login ()方法登陸ftp
       ftp.setFileType(FTPClient.ASCII_FILE_TYPE);// 設置文件類型setFileType()設置ftp文件類型
      } catch (Exception e1) 
      {
       log.error(“faile to load!!!!”);
      }
     } catch (SocketException e1) 
     {
      log.error(“建立連接FTP連接失敗”);
     } catch (IOException e1) 
     {
      log.error(“IO異常FTP.txt讀取失敗”);
     }
    }

  /**************下載文件***************************/


 public void downloadFiles()

{

      // 進入FTP服務器工作目錄
      ftp.changeWorkingDirectory(ftp.printWorkingDirectory()+ remote_dir); // remote_dir FTP遠程文件目錄

       // 獲得遠程ftp目錄下的文件列表
       FTPFile[] fileList = ftp.listFiles(“.”); //  . 號可替換成文件指定ftp目錄。獲取FTPfile文件列表。注意:文件列表包含文件夾及文件

       String[] files = ftp.listNames(); // 獲取FTP服務器文件名稱列表。注意:文件列表包含文件夾及文件的名稱。

      /*

    fileList[0].getGroup();   // 文件所屬組 ,對應有set

    fileList[0].getName();  // 文件名稱, setName(“”)重命名
    fileList[0].getSize();   // 文件大小 返回long數據類型
    fileList[0].getTimestamp().getTime();   //文件最後修改時間
    fileList[0].getType(); //文件類型
    fileList[0].getUser(); //文件所屬用戶
    
    fileList[0].isDirectory(); // 文件是不是文件夾
    fileList[0].isFile();  //判斷是不是 文件
    fileList[0].isSymbolicLink();  // ???
    fileList[0].isUnknown();  // ?、、
    fileList[0].DIRECTORY_TYPE;  //屬性,文件夾類型 返回int型
    fileList[0].FILE_TYPE;  // 屬性, 文件類型, 返回int型
    fileList[0].GROUP_ACCESS;  //組, 返回int型

    */

  //下載指定文件的時候,要判斷指定文件的名稱,比如下載,AA.TXT文件

  //遍歷獲取的FTP文件名稱列表

    for(int i ; i < fileList.length (標註: 或者files.length ); i ++ )

   {

       //判斷文件名是否包含AA.txt的。注意:在 Linux裏 fileList 對象獲取不到length屬性。必須通過files屬性獲取。判斷文件名稱列表也必須從files數組中獲取。

       if(fileList[i].getName().indexOf(“AA.txt”) != -1)

        {

           File  localfile = new File(local_dir+”/”+fileList[i].getName());

           OutPutStream ops = FileOutputStream(localFile);

           

           ftp.retrieveFile(fileList[i].getName(), ops);  //將FTP上指定文件名稱的文件,下載到本地指定輸出流的文件夾中。

           ops.close();

          

        }        

   }

            

}

/******************上傳指定文件***********************/

/**
  * Description: 向FTP服務器上傳文件
  * @Version1.0 Jul 27, 2008 4:31:09 PM by 崔紅保([email protected])創建
  * @param url FTP服務器hostname
  * @param port FTP服務器端口
  * @param username FTP登錄賬號
  * @param password FTP登錄密碼
  * @param path FTP服務器保存目錄
  * @param filename 上傳到FTP服務器上的文件名
  * @param input 輸入流
  * @return 成功返回true,否則返回false
  */
 public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {
  boolean success = false;
  FTPClient ftp = new FTPClient();
  try {
   int reply;
   ftp.connect(url, port);//連接FTP服務器
   //如果採用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器
   ftp.login(username, password);//登錄
   reply = ftp.getReplyCode();
   if (!FTPReply.isPositiveCompletion(reply)) {
    ftp.disconnect();
    return success;
   }
   ftp.changeWorkingDirectory(path);
   ftp.storeFile(filename, input);   
   
   input.close();
   ftp.logout();
   success = true;
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (ftp.isConnected()) {
    try {
     ftp.disconnect();
    } catch (IOException ioe) {
    }
   }
  }
  return success;
 }

@Test
 public void testUpLoadFromDisk(){
  try {
   FileInputStream in=new FileInputStream(new File(“D:/test.txt”));
   boolean flag = uploadFile(“127.0.0.1”, 21, “test”, “test”, “D:/ftp”, “test.txt”, in);
   System.out.println(flag);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  }
 }

 案例一:

 用apache FTP client實現FTP客戶端–支持斷點續傳和中文文件

利用org.apache.commons.Net.ftp包實現一個簡單的ftp客戶端實用類。主要實現一下功能

1.支持上傳下載。支持斷點續傳

2.支持進度彙報

3.支持對於中文目錄及中文文件創建的支持。 

枚舉類UploadStatus代碼

 

[java] view plaincopy
  1.  1public enum UploadStatus {       
  2.  2.     Create_Directory_Fail,      //遠程服務器相應目錄創建失敗       
  3.  3.     Create_Directory_Success,   //遠程服務器闖將目錄成功       
  4.  4.     Upload_New_File_Success,    //上傳新文件成功       
  5.  5.     Upload_New_File_Failed,     //上傳新文件失敗       
  6.  6.     File_Exits,                 //文件已經存在       
  7.  7.     Remote_Bigger_Local,        //遠程文件大於本地文件       
  8.  8.     Upload_From_Break_Success,  //斷點續傳成功       
  9.  9.     Upload_From_Break_Failed,   //斷點續傳失敗       
  10. 10.     Delete_Remote_Faild;        //刪除遠程文件失敗       
  11. 11. }    

 

 

枚舉類DownloadStatus代碼

 

[c-sharp] view plaincopy
  1. 1. public enum DownloadStatus {       
  2. 2.     Remote_File_Noexist,    //遠程文件不存在       
  3. 3.     Local_Bigger_Remote,    //本地文件大於遠程文件       
  4. 4.     Download_From_Break_Success,    //斷點下載文件成功       
  5. 5.     Download_From_Break_Failed,     //斷點下載文件失敗       
  6. 6.     Download_New_Success,           //全新下載文件成功       
  7. 7.     Download_New_Failed;            //全新下載文件失敗       
  8. 8. }    

 

 

 

 

核心FTP代碼

 

[c-sharp] view plaincopy
  1. 核心FTP代碼  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.OutputStream;  
  8. import java.io.PrintWriter;  
  9. import java.io.RandomAccessFile;  
  10.   
  11. import open.mis.data.DownloadStatus;  
  12. import open.mis.data.UploadStatus;  
  13.   
  14. import org.apache.commons.net.PrintCommandListener;  
  15. import org.apache.commons.net.ftp.FTP;  
  16. import org.apache.commons.net.ftp.FTPClient;  
  17. import org.apache.commons.net.ftp.FTPFile;  
  18. import org.apache.commons.net.ftp.FTPReply;  
  19.   
  20. /** 
  21. * 支持斷點續傳的FTP實用類 
  22. * @author BenZhou 
  23. * @version 0.1 實現基本斷點上傳下載 
  24. * @version 0.2 實現上傳下載進度彙報 
  25. * @version 0.3 實現中文目錄創建及中文文件創建,添加對於中文的支持 
  26. */  
  27. public class ContinueFTP {  
  28. public FTPClient ftpClient = new FTPClient();  
  29.   
  30. public ContinueFTP(){  
  31.    //設置將過程中使用到的命令輸出到控制檯  
  32.    this.ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));  
  33. }  
  34.   
  35. /** 
  36. * 連接到FTP服務器 
  37. * @param hostname 主機名 
  38. * @param port 端口 
  39. * @param username 用戶名 
  40. * @param password 密碼 
  41. * @return 是否連接成功 
  42. * @throws IOException 
  43. */  
  44. public boolean connect(String hostname,int port,String username,String password) throws IOException{  
  45.    ftpClient.connect(hostname, port);  
  46.    ftpClient.setControlEncoding(”GBK”);  
  47.    if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){  
  48.     if(ftpClient.login(username, password)){  
  49.      return true;  
  50.     }  
  51.    }  
  52.    disconnect();  
  53.    return false;  
  54. }  
  55.   
  56. /** 
  57. * 從FTP服務器上下載文件,支持斷點續傳,上傳百分比彙報 
  58. * @param remote 遠程文件路徑 
  59. * @param local 本地文件路徑 
  60. * @return 上傳的狀態 
  61. * @throws IOException 
  62. */  
  63. public DownloadStatus download(String remote,String local) throws IOException{  
  64.    //設置被動模式  
  65.    ftpClient.enterLocalPassiveMode();  
  66.    //設置以二進制方式傳輸  
  67.    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  68.    DownloadStatus result;  
  69.     
  70.    //檢查遠程文件是否存在  
  71.    FTPFile[] files = ftpClient.listFiles(new String(remote.getBytes(“GBK”),“iso-8859-1”));  
  72.    if(files.length != 1){  
  73.     System.out.println(“遠程文件不存在”);  
  74.     return DownloadStatus.Remote_File_Noexist;  
  75.    }  
  76.     
  77.    long lRemoteSize = files[0].getSize();  
  78.    File f = new File(local);  
  79.    //本地存在文件,進行斷點下載  
  80.    if(f.exists()){  
  81.     long localSize = f.length();  
  82.     //判斷本地文件大小是否大於遠程文件大小  
  83.     if(localSize >= lRemoteSize){  
  84.      System.out.println(“本地文件大於遠程文件,下載中止”);  
  85.      return DownloadStatus.Local_Bigger_Remote;  
  86.     }  
  87.      
  88.     //進行斷點續傳,並記錄狀態  
  89.     FileOutputStream out = new FileOutputStream(f,true);  
  90.     ftpClient.setRestartOffset(localSize);  
  91.     InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes(“GBK”),“iso-8859-1”));  
  92.     byte[] bytes = new byte[1024];  
  93.     long step = lRemoteSize /100;  
  94.     long process=localSize /step;  
  95.     int c;  
  96.     while((c = in.read(bytes))!= -1){  
  97.      out.write(bytes,0,c);  
  98.      localSize+=c;  
  99.      long nowProcess = localSize /step;  
  100.      if(nowProcess > process){  
  101.       process = nowProcess;  
  102.       if(process % 10 == 0)  
  103.        System.out.println(“下載進度:”+process);  
  104.       //TODO 更新文件下載進度,值存放在process變量中  
  105.      }  
  106.     }  
  107.     in.close();  
  108.     out.close();  
  109.     boolean isDo = ftpClient.completePendingCommand();  
  110.     if(isDo){  
  111.      result = DownloadStatus.Download_From_Break_Success;  
  112.     }else {  
  113.      result = DownloadStatus.Download_From_Break_Failed;  
  114.     }  
  115.    }else {  
  116.     OutputStream out = new FileOutputStream(f);  
  117.     InputStream in= ftpClient.retrieveFileStream(new String(remote.getBytes(“GBK”),“iso-8859-1”));  
  118.     byte[] bytes = new byte[1024];  
  119.     long step = lRemoteSize /100;  
  120.     long process=0;  
  121.     long localSize = 0L;  
  122.     int c;  
  123.     while((c = in.read(bytes))!= -1){  
  124.      out.write(bytes, 0, c);  
  125.      localSize+=c;  
  126.      long nowProcess = localSize /step;  
  127.      if(nowProcess > process){  
  128.       process = nowProcess;  
  129.       if(process % 10 == 0)  
  130.        System.out.println(“下載進度:”+process);  
  131.       //TODO 更新文件下載進度,值存放在process變量中  
  132.      }  
  133.     }  
  134.     in.close();  
  135.     out.close();  
  136.     boolean upNewStatus = ftpClient.completePendingCommand();  
  137.     if(upNewStatus){  
  138.      result = DownloadStatus.Download_New_Success;  
  139.     }else {  
  140.      result = DownloadStatus.Download_New_Failed;  
  141.     }  
  142.    }  
  143.    return result;  
  144. }  
  145.   
  146. /** 
  147. * 上傳文件到FTP服務器,支持斷點續傳 
  148. * @param local 本地文件名稱,絕對路徑 
  149. * @param remote 遠程文件路徑,使用/home/directory1/subdirectory/file.ext 按照Linux上的路徑指定方式,支持多級目錄嵌套,支持遞歸創建不存在的目錄結構 
  150. * @return 上傳結果 
  151. * @throws IOException 
  152. */  
  153. public UploadStatus upload(String local,String remote) throws IOException{  
  154.    //設置PassiveMode傳輸  
  155.    ftpClient.enterLocalPassiveMode();  
  156.    //設置以二進制流的方式傳輸  
  157.    ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  158.    ftpClient.setControlEncoding(”GBK”);  
  159.    UploadStatus result;  
  160.    //對遠程目錄的處理  
  161.    String remoteFileName = remote;  
  162.    if(remote.contains(“/”)){  
  163.     remoteFileName = remote.substring(remote.lastIndexOf(”/”)+1);  
  164.     //創建服務器遠程目錄結構,創建失敗直接返回  
  165.     if(CreateDirecroty(remote, ftpClient)==UploadStatus.Create_Directory_Fail){  
  166.      return UploadStatus.Create_Directory_Fail;  
  167.     }  
  168.    }  
  169.     
  170.    //檢查遠程是否存在文件  
  171.    FTPFile[] files = ftpClient.listFiles(new String(remoteFileName.getBytes(“GBK”),“iso-8859-1”));  
  172.    if(files.length == 1){  
  173.     long remoteSize = files[0].getSize();  
  174.     File f = new File(local);  
  175.     long localSize = f.length();  
  176.     if(remoteSize==localSize){  
  177.      return UploadStatus.File_Exits;  
  178.     }else if(remoteSize > localSize){  
  179.      return UploadStatus.Remote_Bigger_Local;  
  180.     }  
  181.      
  182.     //嘗試移動文件內讀取指針,實現斷點續傳  
  183.     result = uploadFile(remoteFileName, f, ftpClient, remoteSize);  
  184.      
  185.     //如果斷點續傳沒有成功,則刪除服務器上文件,重新上傳  
  186.     if(result == UploadStatus.Upload_From_Break_Failed){  
  187.      if(!ftpClient.deleteFile(remoteFileName)){  
  188.       return UploadStatus.Delete_Remote_Faild;  
  189.      }  
  190.      result = uploadFile(remoteFileName, f, ftpClient, 0);  
  191.     }  
  192.    }else {  
  193.     result = uploadFile(remoteFileName, new File(local), ftpClient, 0);  
  194.    }  
  195.    return result;  
  196. }  
  197. /** 
  198. * 斷開與遠程服務器的連接 
  199. * @throws IOException 
  200. */  
  201. public void disconnect() throws IOException{  
  202.    if(ftpClient.isConnected()){  
  203.     ftpClient.disconnect();  
  204.    }  
  205. }  
  206.   
  207. /** 
  208. * 遞歸創建遠程服務器目錄 
  209. * @param remote 遠程服務器文件絕對路徑 
  210. * @param ftpClient FTPClient對象 
  211. * @return 目錄創建是否成功 
  212. * @throws IOException 
  213. */  
  214. public UploadStatus CreateDirecroty(String remote,FTPClient ftpClient) throws IOException{  
  215.    UploadStatus status = UploadStatus.Create_Directory_Success;  
  216.    String directory = remote.substring(0,remote.lastIndexOf(”/”)+1);  
  217.    if(!directory.equalsIgnoreCase(“/”)&&!ftpClient.changeWorkingDirectory(new String(directory.getBytes(“GBK”),“iso-8859-1”))){  
  218.     //如果遠程目錄不存在,則遞歸創建遠程服務器目錄  
  219.     int start=0;  
  220.     int end = 0;  
  221.     if(directory.startsWith(“/”)){  
  222.      start = 1;  
  223.     }else{  
  224.      start = 0;  
  225.     }  
  226.     end = directory.indexOf(”/”,start);  
  227.     while(true){  
  228.      String subDirectory = new String(remote.substring(start,end).getBytes(“GBK”),“iso-8859-1”);  
  229.      if(!ftpClient.changeWorkingDirectory(subDirectory)){  
  230.       if(ftpClient.makeDirectory(subDirectory)){  
  231.        ftpClient.changeWorkingDirectory(subDirectory);  
  232.       }else {  
  233.        System.out.println(“創建目錄失敗”);  
  234.        return UploadStatus.Create_Directory_Fail;  
  235.       }  
  236.      }  
  237.       
  238.      start = end + 1;  
  239.      end = directory.indexOf(”/”,start);  
  240.       
  241.      //檢查所有目錄是否創建完畢  
  242.      if(end <= start){  
  243.       break;  
  244.      }  
  245.     }  
  246.    }  
  247.    return status;  
  248. }  
  249.   
  250. /** 
  251. * 上傳文件到服務器,新上傳和斷點續傳 
  252. * @param remoteFile 遠程文件名,在上傳之前已經將服務器工作目錄做了改變 
  253. * @param localFile 本地文件File句柄,絕對路徑 
  254. * @param processStep 需要顯示的處理進度步進值 
  255. * @param ftpClient FTPClient引用 
  256. * @return 
  257. * @throws IOException 
  258. */  
  259. public UploadStatus uploadFile(String remoteFile,File localFile,FTPClient ftpClient,long remoteSize) throws IOException{  
  260.    UploadStatus status;  
  261.    //顯示進度的上傳  
  262.    long step = localFile.length() / 100;  
  263.    long process = 0;  
  264.    long localreadbytes = 0L;  
  265.    RandomAccessFile raf = new RandomAccessFile(localFile,“r”);  
  266.    OutputStream out = ftpClient.appendFileStream(new String(remoteFile.getBytes(“GBK”),“iso-8859-1”));  
  267.    //斷點續傳  
  268.    if(remoteSize>0){  
  269.     ftpClient.setRestartOffset(remoteSize);  
  270.     process = remoteSize /step;  
  271.     raf.seek(remoteSize);  
  272.     localreadbytes = remoteSize;  
  273.    }  
  274.    byte[] bytes = new byte[1024];  
  275.    int c;  
  276.    while((c = raf.read(bytes))!= -1){  
  277.     out.write(bytes,0,c);  
  278.     localreadbytes+=c;  
  279.     if(localreadbytes / step != process){  
  280.      process = localreadbytes / step;  
  281.      System.out.println(“上傳進度:” + process);  
  282.      //TODO 彙報上傳狀態  
  283.     }  
  284.    }  
  285.    out.flush();  
  286.    raf.close();  
  287.    out.close();  
  288.    boolean result =ftpClient.completePendingCommand();  
  289.    if(remoteSize > 0){  
  290.     status = result?UploadStatus.Upload_From_Break_Success:UploadStatus.Upload_From_Break_Failed;  
  291.    }else {  
  292.     status = result?UploadStatus.Upload_New_File_Success:UploadStatus.Upload_New_File_Failed;  
  293.    }  
  294.    return status;  
  295. }  
  296.   
  297. public static void main(String[] args) {  
  298.    ContinueFTP myFtp = new ContinueFTP();  
  299.    try {  
  300.     myFtp.connect(”192.168.21.181”, 21, “nid”“123”);  
  301. //    myFtp.ftpClient.makeDirectory(new String(“電視劇”.getBytes(“GBK”),”iso-8859-1”));  
  302. //    myFtp.ftpClient.changeWorkingDirectory(new String(“電視劇”.getBytes(“GBK”),”iso-8859-1”));  
  303. //    myFtp.ftpClient.makeDirectory(new String(“走西口”.getBytes(“GBK”),”iso-8859-1”));  
  304. //    System.out.println(myFtp.upload(“E://yw.flv”, ”/yw.flv”,5));  
  305. //    System.out.println(myFtp.upload(“E://走西口24.mp4”,”/央視走西口/新浪網/走西口24.mp4”));  
  306.     System.out.println(myFtp.download(“/央視走西口/新浪網/走西口24.mp4”“E://走西口242.mp4”));  
  307.     myFtp.disconnect();  
  308.    } catch (IOException e) {  
  309.     System.out.println(“連接FTP出錯:”+e.getMessage());  
  310.    }  
  311. }  
  312. }  



案例二:

ftp 用法:

FTP客戶端

package cm;
import Java.io.File;

import java.io.IOException;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class FtpHelper {
  private FTPClient ftpClient = new FTPClient();

  /**
      * 連接到FTP服務器
      *
      * @param hostname
      *            主機名
      * @param port
      *            端口
      * @param username
      *            用戶名
      * @param password
      *            密碼
      * @return 是否連接成功
      * @throws IOException
      */
     public boolean connect(String hostname, int port, String username,
             String password) throws IOException {
         ftpClient.connect(hostname, port);
         ftpClient.setControlEncoding(“GBK”);
         if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
             if (ftpClient.login(username, password)) {
                 return true;
             }
         }
         disconnect();
         return false;
     }

     /**
      * 從FTP服務器上下載文件,支持斷點續傳,上傳百分比彙報
      *
      * @param remote
      *            遠程文件路徑
      * @param local
      *            本地文件路徑
      * @return 上傳的狀態
      * @throws IOException
      */
     public DownloadStatus download(String remote, String local)
             throws IOException {
         // 設置被動模式
         ftpClient.enterLocalPassiveMode();
         // 設置以二進制方式傳輸
         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
         DownloadStatus result;

         // 檢查遠程文件是否存在
         FTPFile[] files = ftpClient.listFiles(new String(
                 remote.getBytes(“GBK”), “iso-8859-1”));
         if (files.length != 1) {
             System.out.println(“遠程文件不存在”);
             return DownloadStatus.Remote_File_Noexist;
         }

         long lRemoteSize = files[0].getSize();
         File f = new File(local);
         // 本地存在文件,進行斷點下載
         if (f.exists()) {
             long localSize = f.length();
             // 判斷本地文件大小是否大於遠程文件大小
             if (localSize >= lRemoteSize) {
                 System.out.println(“本地文件大於遠程文件,下載中止”);
                 return DownloadStatus.Local_Bigger_Remote;
             }

             // 進行斷點續傳,並記錄狀態
             FileOutputStream out = new FileOutputStream(f, true);
             ftpClient.setRestartOffset(localSize);
             InputStream in = ftpClient.retrieveFileStream(new String(remote
                     .getBytes(“GBK”), “iso-8859-1”));
             byte[] bytes = new byte[1024];
             long step = lRemoteSize / 100;
             long process = localSize / step;
             int c;
             while ((c = in.read(bytes)) != -1) {
                 out.write(bytes, 0, c);
                 localSize += c;
                 long nowProcess = localSize / step;
                 if (nowProcess > process) {
                     process = nowProcess;
                     if (process % 10 == 0)
                         System.out.println(“下載進度:” + process);
                     // TODO 更新文件下載進度,值存放在process變量中
                 }
             }
             in.close();
             out.close();
             boolean isDo = ftpClient.completePendingCommand();
             if (isDo) {
                 result = DownloadStatus.Download_From_Break_Success;
             } else {
                 result = DownloadStatus.Download_From_Break_Failed;
             }
         } else {
             OutputStream out = new FileOutputStream(f);
             InputStream in = ftpClient.retrieveFileStream(new String(remote
                     .getBytes(“GBK”), “iso-8859-1”));
             byte[] bytes = new byte[1024];
             long step = lRemoteSize / 100;
             long process = 0;
             long localSize = 0L;
             int c;
             while ((c = in.read(bytes)) != -1) {
                 out.write(bytes, 0, c);
                 localSize += c;
                 long nowProcess = localSize / step;
                 if (nowProcess > process) {
                     process = nowProcess;
                     if (process % 10 == 0)
                         System.out.println(“下載進度:” + process);
                     // TODO 更新文件下載進度,值存放在process變量中
                 }
             }
             in.close();
             out.close();
             boolean upNewStatus = ftpClient.completePendingCommand();
             if (upNewStatus) {
                 result = DownloadStatus.Download_New_Success;
             } else {
                 result = DownloadStatus.Download_New_Failed;
             }
         }
         return result;
     }

     /**
      * 上傳文件到FTP服務器,支持斷點續傳
      *
      * @param local
      *            本地文件名稱,絕對路徑
      * @param remote
      *            遠程文件路徑,使用/home/directory1/subdirectory/file.ext
      *            按照linux上的路徑指定方式,支持多級目錄嵌套,支持遞歸創建不存在的目錄結構
      * @return 上傳結果
      * @throws IOException
      */
     public UploadStatus upload(String local, String remote) throws IOException {
         // 設置PassiveMode傳輸
         ftpClient.enterLocalPassiveMode();
         // 設置以二進制流的方式傳輸
         ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
         ftpClient.setControlEncoding(“GBK”);
         UploadStatus result;
         // 對遠程目錄的處理
         String remoteFileName = remote;
         if (remote.contains(“/”)) {
             remoteFileName = remote.substring(remote.lastIndexOf(“/”) + 1);
             // 創建服務器遠程目錄結構,創建失敗直接返回
             if (createDirecroty(remote, ftpClient) == UploadStatus.Create_Directory_Fail) {
                 return UploadStatus.Create_Directory_Fail;
             }
         }
         //ftpClient.feat();

 //      System.out.println( ftpClient.getReply());
 //      System.out.println( ftpClient.acct(null));
 //      System.out.println(ftpClient.getReplyCode());
 //      System.out.println(ftpClient.getReplyString());


         // 檢查遠程是否存在文件
         FTPFile[] files = ftpClient.listFiles(new String(remoteFileName
                 .getBytes(“GBK”), “iso-8859-1”));
         if (files.length == 1) {
             long remoteSize = files[0].getSize();
             File f = new File(local);
             long localSize = f.length();
             if (remoteSize == localSize) { // 文件存在
                 return UploadStatus.File_Exits;
             } else if (remoteSize > localSize) {
                 return UploadStatus.Remote_Bigger_Local;
             }

             // 嘗試移動文件內讀取指針,實現斷點續傳
             result = uploadFile(remoteFileName, f, ftpClient, remoteSize);

             // 如果斷點續傳沒有成功,則刪除服務器上文件,重新上傳
             if (result == UploadStatus.Upload_From_Break_Failed) {
                 if (!ftpClient.deleteFile(remoteFileName)) {
                     return UploadStatus.Delete_Remote_Faild;
                 }
                 result = uploadFile(remoteFileName, f, ftpClient, 0);
             }
         } else {
             result = uploadFile(remoteFileName, new File(local), ftpClient, 0);
         }
         return result;
     }

     /**
      * 斷開與遠程服務器的連接
      *
      * @throws IOException
      */
     public void disconnect() throws IOException {
         if (ftpClient.isConnected()) {
             ftpClient.disconnect();
         }
     }

     /**
      * 遞歸創建遠程服務器目錄
      *
      * @param remote
      *            遠程服務器文件絕對路徑
      * @param ftpClient
      *            FTPClient對象
      * @return 目錄創建是否成功
      * @throws IOException
      */
     public UploadStatus createDirecroty(String remote, FTPClient ftpClient)
             throws IOException {
         UploadStatus status = UploadStatus.Create_Directory_Success;
         String directory = remote.substring(0, remote.lastIndexOf(“/”) + 1);
         if (!directory.equalsIgnoreCase(“/”)
                 && !ftpClient.changeWorkingDirectory(new String(directory
                         .getBytes(“GBK”), “iso-8859-1”))) {
             // 如果遠程目錄不存在,則遞歸創建遠程服務器目錄
             int start = 0;
             int end = 0;
             if (directory.startsWith(“/”)) {
                 start = 1;
             } else {
                 start = 0;
             }
             end = directory.indexOf(“/”, start);
             while (true) {
                 String subDirectory = new String(remote.substring(start, end)
                         .getBytes(“GBK”), “iso-8859-1”);
                 if (!ftpClient.changeWorkingDirectory(subDirectory)) {
                     if (ftpClient.makeDirectory(subDirectory)) {
                         ftpClient.changeWorkingDirectory(subDirectory);
                     } else {
                         System.out.println(“創建目錄失敗”);
                         return UploadStatus.Create_Directory_Fail;
                     }
                 }

                 start = end + 1;
                 end = directory.indexOf(“/”, start);

                 // 檢查所有目錄是否創建完畢
                 if (end <= start) {
                     break;
                 }
             }
         }
         return status;
     }

     /**
      * 上傳文件到服務器,新上傳和斷點續傳
      *
      * @param remoteFile
      *            遠程文件名,在上傳之前已經將服務器工作目錄做了改變
      * @param localFile
      *            本地文件File句柄,絕對路徑
      * @param processStep
      *            需要顯示的處理進度步進值
      * @param ftpClient
      *            FTPClient引用
      * @return
      * @throws IOException
      */
     public UploadStatus uploadFile(String remoteFile, File localFile,
             FTPClient ftpClient, long remoteSize) throws IOException {
         UploadStatus status;
         // 顯示進度的上傳
         long step = localFile.length() / 100;
         long process = 0;
         long localreadbytes = 0L;
         RandomAccessFile raf = new RandomAccessFile(localFile, “r”);
         String remote = new String(remoteFile.getBytes(“GBK”), “iso-8859-1”);
         OutputStream out = ftpClient.appendFileStream(remote);
         if(out==null)
         {
             String message = ftpClient.getReplyString();
             throw new RuntimeException(message);
         }
         // 斷點續傳
         if (remoteSize > 0) {
             ftpClient.setRestartOffset(remoteSize);
             process = remoteSize / step;
             raf.seek(remoteSize);
             localreadbytes = remoteSize;
         }
         byte[] bytes = new byte[1024];
         int c;
         while ((c = raf.read(bytes)) != -1) {
             out.write(bytes, 0, c);
             localreadbytes += c;
             if (localreadbytes / step != process) {
                 process = localreadbytes / step;
                 System.out.println(“上傳進度:” + process);
                 // TODO 彙報上傳狀態

             }
         }
         out.flush();
         raf.close();
         out.close();
         boolean result = ftpClient.completePendingCommand();
         if (remoteSize > 0) {
             status = result ? UploadStatus.Upload_From_Break_Success
                     : UploadStatus.Upload_From_Break_Failed;
         } else {
             status = result ? UploadStatus.Upload_New_File_Success
                     : UploadStatus.Upload_New_File_Failed;
         }
         return status;
     }

     /**
      * 獲取指定目錄下的文件名稱列表
      * @author HQQW510_64
      * @param currentDir 需要獲取其子目錄的當前目錄名稱
      * @return 返回子目錄字符串數組
      */
     public String[] GetFileNames(String currentDir) {
         String[] dirs = null;
         try {
             if(currentDir==null)
             dirs = ftpClient.listNames();
             else
                 dirs = ftpClient.listNames(currentDir);
         } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
         }
         return dirs;
     }

     /**
      * 獲取指定目錄下的文件與目錄信息集合
      * @param currentDir 指定的當前目錄
      * @return 返回的文件集合
      */
     public FTPFile[] GetDirAndFilesInfo(String currentDir)
     {
         FTPFile[] files=null;

         try
         {
             if(currentDir==null)
                 files=ftpClient.listFiles();
             else
              files = ftpClient.listFiles(currentDir);
      }
      catch(IOException ex)
      {
          // TODO Auto-generated catch block
          ex.printStackTrace();
      }
      return files;
 }
}



案例三 

JAVA中使用FTPClient上傳下載

        在JAVA程序中,經常需要和FTP打交道,比如向FTP服務器上傳文件、下載文件,本文簡單介紹如何利用jakarta commons中的FTPClient(在commons-net包中)實現上傳下載文件。

一、上傳文件

         原理就不介紹了,大家直接看代碼吧

[Java] view plaincopy
  1. /** 
  2.  * Description: 向FTP服務器上傳文件 
  3.  * @Version1.0 Jul 27, 2008 4:31:09 PM by 崔紅保([email protected])創建 
  4.  * @param url FTP服務器hostname 
  5.  * @param port FTP服務器端口 
  6.  * @param username FTP登錄賬號 
  7.  * @param password FTP登錄密碼 
  8.  * @param path FTP服務器保存目錄 
  9.  * @param filename 上傳到FTP服務器上的文件名 
  10.  * @param input 輸入流 
  11.  * @return 成功返回true,否則返回false 
  12.  */  
  13. public static boolean uploadFile(String url,int port,String username, String password, String path, String filename, InputStream input) {  
  14.     boolean success = false;  
  15.     FTPClient ftp = new FTPClient();  
  16.     try {  
  17.         int reply;  
  18.         ftp.connect(url, port);//連接FTP服務器  
  19.         //如果採用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器  
  20.         ftp.login(username, password);//登錄  
  21.         reply = ftp.getReplyCode();  
  22.         if (!FTPReply.isPositiveCompletion(reply)) {  
  23.             ftp.disconnect();  
  24.             return success;  
  25.         }  
  26.         ftp.changeWorkingDirectory(path);  
  27.         ftp.storeFile(filename, input);           
  28.           
  29.         input.close();  
  30.         ftp.logout();  
  31.         success = true;  
  32.     } catch (IOException e) {  
  33.         e.printStackTrace();  
  34.     } finally {  
  35.         if (ftp.isConnected()) {  
  36.             try {  
  37.                 ftp.disconnect();  
  38.             } catch (IOException ioe) {  
  39.             }  
  40.         }  
  41.     }  
  42.     return success;  
  43. }<pre></pre>  

 

下面我們寫兩個小例子:

1.將本地文件上傳到FTP服務器上,代碼如下:

[Java] view plaincopy
  1. @Test  
  2. public void testUpLoadFromDisk(){  
  3.     try {  
  4.         FileInputStream in=new FileInputStream(new File(“D:/test.txt”));  
  5.         boolean flag = uploadFile(“127.0.0.1”21“test”“test”“D:/ftp”“test.txt”, in);  
  6.         System.out.println(flag);  
  7.     } catch (FileNotFoundException e) {  
  8.         e.printStackTrace();  
  9.     }  
  10. }<pre></pre>  

2.在FTP服務器上生成一個文件,並將一個字符串寫入到該文件中

[Java] view plaincopy
  1. @Test  
  2. public void testUpLoadFromString(){  
  3.     try {  
  4.         InputStream input = new ByteArrayInputStream(“test ftp”.getBytes(“utf-8”));  
  5.         boolean flag = uploadFile(“127.0.0.1”21“test”“test”“D:/ftp”“test.txt”, input);  
  6.         System.out.println(flag);  
  7.     } catch (UnsupportedEncodingException e) {  
  8.         e.printStackTrace();  
  9.     }  
  10. }<pre></pre>  


二、下載文件

       從FTP服務器下載文件的代碼也很簡單,參考如下:

[Java] view plaincopy
  1. /** 
  2.  * Description: 從FTP服務器下載文件 
  3.  * @Version1.0 Jul 27, 2008 5:32:36 PM by 崔紅保([email protected])創建 
  4.  * @param url FTP服務器hostname 
  5.  * @param port FTP服務器端口 
  6.  * @param username FTP登錄賬號 
  7.  * @param password FTP登錄密碼 
  8.  * @param remotePath FTP服務器上的相對路徑 
  9.  * @param fileName 要下載的文件名 
  10.  * @param localPath 下載後保存到本地的路徑 
  11.  * @return 
  12.  */  
  13. public static boolean downFile(String url, int port,String username, String password, String remotePath,String fileName,String localPath) {  
  14.     boolean success = false;  
  15.     FTPClient ftp = new FTPClient();  
  16.     try {  
  17.         int reply;  
  18.         ftp.connect(url, port);  
  19.         //如果採用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器  
  20.         ftp.login(username, password);//登錄  
  21.         reply = ftp.getReplyCode();  
  22.         if (!FTPReply.isPositiveCompletion(reply)) {  
  23.             ftp.disconnect();  
  24.             return success;  
  25.         }  
  26.         ftp.changeWorkingDirectory(remotePath);//轉移到FTP服務器目錄  
  27.         FTPFile[] fs = ftp.listFiles();  
  28.         for(FTPFile ff:fs){  
  29.             if(ff.getName().equals(fileName)){  
  30.                 File localFile = new File(localPath+“/”+ff.getName());  
  31.                   
  32.                 OutputStream is = new FileOutputStream(localFile);   
  33.                 ftp.retrieveFile(ff.getName(), is);  
  34.                 is.close();  
  35.             }  
  36.         }  
  37.           
  38.         ftp.logout();  
  39.         success = true;  
  40.     } catch (IOException e) {  
  41.         e.printStackTrace();  
  42.     } finally {  
  43.         if (ftp.isConnected()) {  
  44.             try {  
  45.                 ftp.disconnect();  
  46.             } catch (IOException ioe) {  
  47.             }  
  48.         }  
  49.     }  
  50.     return success;  
  51. }<pre></pre>  



案例三:

  1. /** 
  2.  * 支持斷點續傳的FTP實用類  
  3.  *  
  4.  * @author chenxin 
  5.  * @version [版本號, 2012-5-21] 
  6.  * @see [相關類/方法] 
  7.  * @since [產品/模塊版本] 
  8.  */  
  9. public class FtpUtils  {  
  10.   
  11.     private FTPClient ftpClient = null;  
  12.    private static final Logger logger = Logger.getLogger(FtpUtils.class);  
  13.    private String hostname;  
  14.    private String username;  
  15.    private String password;  
  16.    private int port;  
  17.    private static final String EPUB_DIR = “epub_file”;  
  18.      
  19.    public FtpUtils()  
  20.    {  
  21.        ftpClient = new FTPClient();  
  22.        username = ServerConfig.get(”ftp/ftp-user”“”);  
  23.        password = ServerConfig.get(”ftp/ftp-password”“”);  
  24.        hostname = ServerConfig.get(”ftp/ftp-host”“”);  
  25.        port = ServerConfig.getInt(”ftp/ftp-port”21);  
  26. //       {     
  27. //           //設置將過程中使用到的命令輸出到控制檯     
  28. //           ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));     
  29. //       }   
  30.    }    
  31.         
  32.    /**   
  33.     * 連接到FTP服務器  
  34.     * @param hostname 主機名  
  35.     * @param port 端口  
  36.     * @param username 用戶名  
  37.     * @param password 密碼  
  38.     * @return 是否連接成功  
  39.     * @throws IOException  
  40.     */    
  41.    public boolean connect() throws IOException{    
  42.        ftpClient.connect(hostname, port);     
  43.        ftpClient.setControlEncoding(ServerConfig.get(”ftp/ftp-charset”“GBK”));     
  44.        if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){     
  45.            if(ftpClient.login(username, password)){    
  46.                // 設置被動模式  
  47.                ftpClient.enterLocalPassiveMode();  
  48.                // 設置以二進制方式傳輸  
  49.                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  50.                return true;     
  51.            }     
  52.        }     
  53.        disconnect();     
  54.        return false;     
  55.    }     
  56.      
  57.    public boolean reconnect() throws IOException  
  58.    {    
  59.          disconnect();    
  60.          ftpClient.connect(hostname, port);     
  61.          ftpClient.setControlEncoding(ServerConfig.get(”ftp/ftp-charset”“GBK”));     
  62.          if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){     
  63.              if(ftpClient.login(username, password)){    
  64.                  // 設置被動模式  
  65.                  ftpClient.enterLocalPassiveMode();  
  66.                  // 設置以二進制方式傳輸  
  67.                  ftpClient.setFileType(FTP.BINARY_FILE_TYPE);  
  68.                  return true;     
  69.              }     
  70.          }     
  71.          disconnect();     
  72.          return false;     
  73.  }     
  74.         
  75.  /** 
  76.   * 從FTP服務器上下載文件,上傳百分比 
  77.   * @param remote 
  78.   * @param dir 
  79.   * @param fileName 
  80.   * @return 
  81.   * @throws IOException 
  82.   * @see [類、類#方法、類#成員] 
  83.   */  
  84.     public boolean download(String remote, String dir, String fileName)  
  85.         throws IOException  
  86.     {  
  87.         File file = new File(dir + File.separator + fileName);  
  88.         // 本地存在文件  
  89.         if (file.exists())  
  90.         {  
  91.             if (logger.isDebugEnabled())  
  92.             {  
  93.                 logger.debug(”File is existsed.”);  
  94.             }  
  95.             // 如果文件存在,但還未從FTP服務器上完全取下來,則需要等待  
  96.             Long initialSize = 0L;  
  97.             int i = 0;  
  98.             while (initialSize != file.length())  
  99.             {  
  100.                 i++;  
  101.                 initialSize = file.length();  
  102.                 try  
  103.                 {  
  104.                     Thread.sleep(100L);  
  105.                 }  
  106.                 catch (InterruptedException e)  
  107.                 {  
  108.                     e.printStackTrace();  
  109.                 }  
  110.             }  
  111.               
  112.             if (i > 1)  
  113.             {  
  114.                 // 如果是剛下完的文件,則不需要再比對大小是否一致  
  115.                 return true;  
  116.             }  
  117.         }  
  118.           
  119.         Long localSize = file.length();  
  120.         File localDir = new File(dir);  
  121.         if (!localDir.exists())  
  122.         {  
  123.             localDir.mkdirs();  
  124.         }  
  125.           
  126.         // 檢查遠程文件是否存在  
  127.         if (remote.startsWith(“/”))  
  128.         {  
  129.             remote = remote.substring(1);  
  130.         }  
  131.           
  132.         if (ftpClient.listNames(remote).length <= 0)  
  133.         {     
  134.             // 文件不存在  
  135.             logger.error(”Could not find file from ftp server: ” + remote);  
  136.             return false;  
  137.         }  
  138.           
  139.         // 計算遠程文件大小  
  140.         String s = ”SIZE ” + remote + “\r\n”;  
  141.         ftpClient.sendCommand(s);  
  142.         String s1 = ftpClient.getReplyString();  
  143.         Long remoteSize = Long.parseLong(s1.substring(3).trim());  
  144.         if (logger.isDebugEnabled())  
  145.         {  
  146.             logger.debug(”localsize: ” + localSize + “, remoteSize: ” + remoteSize);  
  147.         }  
  148.         if (remoteSize.equals(localSize))  
  149.         {  
  150.             if (logger.isDebugEnabled())  
  151.             {  
  152.                 logger.debug(”File’s size not changed.”);  
  153.             }  
  154.             return true;  
  155.         }  
  156.         else if (localSize != 0L)  
  157.         {  
  158.             if (logger.isDebugEnabled())  
  159.             {  
  160.                 logger.debug(”File’s size changed which needed re-download.”);  
  161.             }  
  162.             //遠程文件和本地文件大小不一致,則刪除本地文件  
  163.             file.delete();  
  164.             //如果是EPUB書路徑,則需要把解壓過的臨時文件也一併刪除  
  165.             if (dir.indexOf(EPUB_DIR) > 0)  
  166.             {  
  167.                 deleteAll(localDir);  
  168.             }  
  169.         }  
  170.           
  171.         // 重連以回到根目錄  
  172.         reconnect();  
  173.         OutputStream out = new FileOutputStream(file);  
  174.         InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes(“UTF-8”),  
  175.             ServerConfig.get(”ftp/ftp-charset”“GBK”)));  
  176.         if (logger.isDebugEnabled())  
  177.         {  
  178.             logger.debug(”Begin to downloaded file from ftp.”);  
  179.         }  
  180.         byte[] bytes = new byte[1024];  
  181.         int count;  
  182.         while ((count = in.read(bytes)) != -1)  
  183.         {  
  184.             out.write(bytes, 0, count);  
  185.         }  
  186.         if (logger.isDebugEnabled())  
  187.         {  
  188.             logger.debug(”File has been downloaded from ftp successfully.”);  
  189.         }  
  190.         in.close();  
  191.         out.close();  
  192.         boolean upNewStatus = ftpClient.completePendingCommand();  
  193.         if (upNewStatus)  
  194.         {  
  195.             return true;  
  196.         }  
  197.         else  
  198.         {  
  199.             return false;  
  200.         }  
  201.     }  
  202.       
  203.     //遞歸刪除文件夾  
  204.     private void deleteAll(File file)  
  205.     {  
  206.         if (file.isDirectory() && !ArrayUtils.isEmpty(file.list()))  
  207.         {  
  208.             for (File childFile : file.listFiles())  
  209.             {  
  210.                 deleteAll(childFile);  
  211.             }  
  212.         }  
  213.         else  
  214.         {  
  215.             file.delete();  
  216.         }  
  217.     }  
  218.   
  219.     /** *//**  
  220.      * 斷開與遠程服務器的連接  
  221.      * @throws IOException  
  222.      */    
  223.     public void disconnect() throws IOException{     
  224.         if(ftpClient.isConnected()){     
  225.             ftpClient.disconnect();     
  226.         }     
  227.     }     
  228.          
  229.     public static void main(String[] args) {     
  230.         FtpUtils myFtp = new FtpUtils();     
  231.         try {     
  232.             myFtp.connect();     
  233.             System.out.println(myFtp.download(”/央視走西口/新浪網/走西口24.mp4”“E:\\走西口242.mp4”“123”));     
  234.             myFtp.disconnect();     
  235.         } catch (IOException e) {     
  236.             System.out.println(”連接FTP出錯:”+e.getMessage());     
  237.         }     
  238.     }   
  239.   
  240.   
  241.   
  242.         //使用: 下載文件  
  243.         FtpUtils ftpUtils = new FtpUtils();  
  244.         ftpUtils.connect();  
  245.         ftpUtils.download(fileUrl, directoryPath, filename);  
  246.         ftpUtils.disconnect();  
  247.   
  248.   
  249.   
  250.   
  251. }  
/**
 * 支持斷點續傳的FTP實用類 
 * 
 * @author chenxin
 * @version [版本號, 2012-5-21]
 * @see [相關類/方法]
 * @since [產品/模塊版本]
 */
public class FtpUtils  {

    private FTPClient ftpClient = null;
   private static final Logger logger = Logger.getLogger(FtpUtils.class);
   private String hostname;
   private String username;
   private String password;
   private int port;
   private static final String EPUB_DIR = "epub_file";

   public FtpUtils()
   {
       ftpClient = new FTPClient();
       username = ServerConfig.get("ftp/ftp-user", "");
       password = ServerConfig.get("ftp/ftp-password", "");
       hostname = ServerConfig.get("ftp/ftp-host", "");
       port = ServerConfig.getInt("ftp/ftp-port", 21);
//       {   
//           //設置將過程中使用到的命令輸出到控制檯   
//           ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));   
//       } 
   }  

   /**  
    * 連接到FTP服務器 
    * @param hostname 主機名 
    * @param port 端口 
    * @param username 用戶名 
    * @param password 密碼 
    * @return 是否連接成功 
    * @throws IOException 
    */  
   public boolean connect() throws IOException{  
       ftpClient.connect(hostname, port);   
       ftpClient.setControlEncoding(ServerConfig.get("ftp/ftp-charset", "GBK"));   
       if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){   
           if(ftpClient.login(username, password)){  
               // 設置被動模式
               ftpClient.enterLocalPassiveMode();
               // 設置以二進制方式傳輸
               ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
               return true;   
           }   
       }   
       disconnect();   
       return false;   
   }   

   public boolean reconnect() throws IOException
   {  
         disconnect();  
         ftpClient.connect(hostname, port);   
         ftpClient.setControlEncoding(ServerConfig.get("ftp/ftp-charset", "GBK"));   
         if(FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){   
             if(ftpClient.login(username, password)){  
                 // 設置被動模式
                 ftpClient.enterLocalPassiveMode();
                 // 設置以二進制方式傳輸
                 ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                 return true;   
             }   
         }   
         disconnect();   
         return false;   
 }   

 /**
  * 從FTP服務器上下載文件,上傳百分比
  * @param remote
  * @param dir
  * @param fileName
  * @return
  * @throws IOException
  * @see [類、類#方法、類#成員]
  */
    public boolean download(String remote, String dir, String fileName)
        throws IOException
    {
        File file = new File(dir + File.separator + fileName);
        // 本地存在文件
        if (file.exists())
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("File is existsed.");
            }
            // 如果文件存在,但還未從FTP服務器上完全取下來,則需要等待
            Long initialSize = 0L;
            int i = 0;
            while (initialSize != file.length())
            {
                i++;
                initialSize = file.length();
                try
                {
                    Thread.sleep(100L);
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }

            if (i > 1)
            {
                // 如果是剛下完的文件,則不需要再比對大小是否一致
                return true;
            }
        }

        Long localSize = file.length();
        File localDir = new File(dir);
        if (!localDir.exists())
        {
            localDir.mkdirs();
        }

        // 檢查遠程文件是否存在
        if (remote.startsWith("/"))
        {
            remote = remote.substring(1);
        }

        if (ftpClient.listNames(remote).length <= 0)
        {   
            // 文件不存在
            logger.error("Could not find file from ftp server: " + remote);
            return false;
        }

        // 計算遠程文件大小
        String s = "SIZE " + remote + "\r\n";
        ftpClient.sendCommand(s);
        String s1 = ftpClient.getReplyString();
        Long remoteSize = Long.parseLong(s1.substring(3).trim());
        if (logger.isDebugEnabled())
        {
            logger.debug("localsize: " + localSize + ", remoteSize: " + remoteSize);
        }
        if (remoteSize.equals(localSize))
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("File's size not changed.");
            }
            return true;
        }
        else if (localSize != 0L)
        {
            if (logger.isDebugEnabled())
            {
                logger.debug("File's size changed which needed re-download.");
            }
            //遠程文件和本地文件大小不一致,則刪除本地文件
            file.delete();
            //如果是EPUB書路徑,則需要把解壓過的臨時文件也一併刪除
            if (dir.indexOf(EPUB_DIR) > 0)
            {
                deleteAll(localDir);
            }
        }

        // 重連以回到根目錄
        reconnect();
        OutputStream out = new FileOutputStream(file);
        InputStream in = ftpClient.retrieveFileStream(new String(remote.getBytes("UTF-8"),
            ServerConfig.get("ftp/ftp-charset", "GBK")));
        if (logger.isDebugEnabled())
        {
            logger.debug("Begin to downloaded file from ftp.");
        }
        byte[] bytes = new byte[1024];
        int count;
        while ((count = in.read(bytes)) != -1)
        {
            out.write(bytes, 0, count);
        }
        if (logger.isDebugEnabled())
        {
            logger.debug("File has been downloaded from ftp successfully.");
        }
        in.close();
        out.close();
        boolean upNewStatus = ftpClient.completePendingCommand();
        if (upNewStatus)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    //遞歸刪除文件夾
    private void deleteAll(File file)
    {
        if (file.isDirectory() && !ArrayUtils.isEmpty(file.list()))
        {
            for (File childFile : file.listFiles())
            {
                deleteAll(childFile);
            }
        }
        else
        {
            file.delete();
        }
    }

    /** *//** 
     * 斷開與遠程服務器的連接 
     * @throws IOException 
     */  
    public void disconnect() throws IOException{   
        if(ftpClient.isConnected()){   
            ftpClient.disconnect();   
        }   
    }   

    public static void main(String[] args) {   
        FtpUtils myFtp = new FtpUtils();   
        try {   
            myFtp.connect();   
            System.out.println(myFtp.download("/央視走西口/新浪網/走西口24.mp4", "E:\\走西口242.mp4", "123"));   
            myFtp.disconnect();   
        } catch (IOException e) {   
            System.out.println("連接FTP出錯:"+e.getMessage());   
        }   
    } 



        //使用: 下載文件
        FtpUtils ftpUtils = new FtpUtils();
        ftpUtils.connect();
        ftpUtils.download(fileUrl, directoryPath, filename);
        ftpUtils.disconnect();




}


案例四

sun.net.ftp.FtpClient.,該類庫主要提供了用於建立FTP連接的類。利用這些類的方法,編程人員可以遠程登錄到FTP服務器,列舉該服務器上的目錄,設置傳輸協議,以及傳送文件。FtpClient類涵蓋了幾乎所有FTP的功能,FtpClient的實例變量保存了有關建立”代理”的各種信息。下面給出了這些實例變量。


直接給大家上代碼,想要用功能的直接拿過來用接可以:

  1. import java.io.BufferedInputStream;  
  2. import java.io.BufferedReader;  
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.InputStreamReader;  
  9. import java.io.OutputStream;  
  10. import java.sql.Connection;  
  11. import java.sql.Statement;  
  12. import java.util.ArrayList;  
  13. import java.util.List;  
  14. import java.util.Vector;  
  15.   
  16. import org.apache.commons.net.ftp.FTPClient;  
  17. import org.apache.commons.net.ftp.FTPFile;  
  18. import org.apache.commons.net.ftp.FTPReply;  
  19.   
  20.   
  21.   
  22. public class TfpTools {  
  23.     //連接ftp  
  24.     private FTPClient ftpClient = null;  
  25. //    public static String ip = “117.21.208.37”;  
  26. //    public static int port = 21;  
  27. //    public static String username = “eftp”;  
  28. //    public static String password = “e1f2t3p4”;  
  29. //    public static String sub_path = ”/opt/tomcat/webapps/photocdn/msgdata/”;  
  30.     /** 
  31.      * 連接ftp 
  32.      */  
  33.     public void connectServer(String ip,int port,String username,String password,String sub_path) throws Exception {  
  34.         int i = 10;  
  35.         if (ftpClient == null) {  
  36.             int reply;  
  37.             while (i > 0) {  
  38.                 try {  
  39.                     ftpClient = new FTPClient();  
  40.                     if (port != 21)  
  41.                         ftpClient.connect(ip, port);  
  42.                     else  
  43.                         ftpClient.connect(ip);  
  44.                     ftpClient.login(username, password);  
  45.                     reply = ftpClient.getReplyCode();  
  46.                     if (!FTPReply.isPositiveCompletion(reply)) {  
  47.                         ftpClient.disconnect();  
  48.                     }  
  49.                     System.out.println(”sub_path==============”+sub_path);  
  50.                     // 對目錄進行轉換  
  51.                     if (ftpClient.changeWorkingDirectory(sub_path)) {  
  52.                     } else {  
  53.                         ftpClient.disconnect();  
  54.                         ftpClient = null;  
  55.                     }  
  56.                 } catch (Exception e) {    
  57.                     e.printStackTrace();  
  58.                     if (0 < i–) {  
  59.                         try {  
  60.                             Thread.sleep(10000);  
  61.                             continue;  
  62.                         } catch (Exception ex) {  
  63.                         }  
  64.                     }  
  65.                 }  
  66.                 i = 0;  
  67.             }  
  68.         }  
  69.     }  
  70.     /** 
  71.      * 文件上傳 
  72.      * @param ip 
  73.      * @param port 
  74.      * @param username 
  75.      * @param password 
  76.      * @param sub_path                遠程文件上傳目錄 
  77.      * @param localFilePath              本地文件存放路徑、、 
  78.      * @param newFileName            遠程生成的文件路徑和文件名 
  79.      * @throws Exception 
  80.      */  
  81.     public void uploadFile(String ip,int port,String username,String password,String sub_path,String localFilePath, String newFileName)throws Exception {  
  82.     BufferedInputStream buffIn = null;  
  83.     try {  
  84.         connectServer(ip,port,username,password,sub_path);        //連接服務器  
  85.         System.out.println(”start upload”);  
  86.         buffIn = new BufferedInputStream(new FileInputStream(localFilePath));  
  87.         System.out.println(”find localFilePath success”);  
  88.         ftpClient.storeFile(newFileName, buffIn);  
  89.         System.out.println(”upload success”);  
  90.     } catch (Exception e) {  
  91.         e.printStackTrace();  
  92.         throw e;  
  93.     } finally {  
  94.         try {  
  95.             if (buffIn != null)  
  96.                 buffIn.close();  
  97.         } catch (Exception e) {  
  98.             e.printStackTrace();  
  99.         }  
  100.     }  
  101.     }  
  102.     /** 
  103.      *  
  104.      * Definition: 讀取txt文件,存放到list中,以便於讀取 
  105.      * author: xiehaoyu 
  106.      * Created date: 2013-6-14 
  107.      * @param readTxt 
  108.      * @return 
  109.      */  
  110.     public static List<String> readTxt(String readTxt){  
  111.         BufferedReader br = null;  
  112.         List<String> list = new ArrayList<String>();  
  113.         try {  
  114.             br = new BufferedReader(new InputStreamReader(new FileInputStream(      
  115.                     new File(readTxt))));  
  116.             String temp = br.readLine();  
  117.             while (temp != null) {  
  118.                 String[] str=temp.toString().trim().split(”\\|”);  
  119.                 for(String s : str){  
  120.                     if(!“”.equals(s))  
  121.                     list.add(s);  
  122.                 }  
  123.                 temp=br.readLine();  
  124.             }  
  125.             br.close();  
  126.         } catch (Exception e1) {  
  127.             e1.printStackTrace();  
  128.         }  
  129.          return list;  
  130.     }  
  131.     public void copyFile(String oldPath, String newPath) {  
  132.         try {  
  133.           int bytesum = 0;  
  134.           int byteread = 0;  
  135.           File oldfile = new File(oldPath);  
  136.           if (oldfile.exists()) { //文件存在時  
  137.             InputStream inStream = new FileInputStream(oldPath); //讀入原文件  
  138.             FileOutputStream fs = new FileOutputStream(newPath);  
  139.             byte[] buffer = new byte[1444];  
  140.             while ( (byteread = inStream.read(buffer)) != -1) {  
  141.               bytesum += byteread; //字節數 文件大小  
  142.               System.out.println(bytesum);  
  143.               fs.write(buffer, 0, byteread);  
  144.             }  
  145.             inStream.close();  
  146.           }  
  147.         }  
  148.         catch (Exception e) {  
  149.           System.out.println(”複製單個文件操作出錯”);  
  150.           e.printStackTrace();  
  151.   
  152.         }  
  153.   
  154.     }  
  155.       
  156.     public void delFile(String filePathAndName) {  
  157.         try {  
  158.           String filePath = filePathAndName;  
  159.           filePath = filePath.toString();  
  160.           java.io.File myDelFile = new java.io.File(filePath);  
  161.           myDelFile.delete();  
  162.         }  
  163.         catch (Exception e) {  
  164.           System.out.println(”刪除文件操作出錯”);  
  165.           e.printStackTrace();  
  166.         }  
  167.     }  
  168.       
  169.     /** 
  170.      * 文件下載。。 
  171.      * @param url                ftp ip 
  172.      * @param port                ftp端口 
  173.      * @param username             
  174.      * @param password 
  175.      * @param remotePath        下載路徑 
  176.      * @param fileName            下載文件中包含什麼文件名 
  177.      * @param localPath            本地存放路徑 
  178.      * @return 
  179.      */  
  180.     public static boolean downFile(  
  181.              String url,  
  182.              int port,  
  183.              String username,  
  184.              String password,  
  185.              String remotePath,  
  186.              String fileName,  
  187.              String localPath){  
  188.      boolean success = false;  
  189.      FTPClient ftp = new FTPClient();  
  190.      try {  
  191.          int reply;  
  192.          ftp.connect(url, port);  
  193.          //如果採用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器   
  194.          ftp.login(username, password);//登錄   
  195.          reply = ftp.getReplyCode();  
  196.          if (!FTPReply.isPositiveCompletion(reply)) {  
  197.          ftp.disconnect();  
  198.          return success;  
  199.          }  
  200.          ftp.changeWorkingDirectory(remotePath);//轉移到FTP服務器目錄  
  201.          FTPFile[] fs = ftp.listFiles();  
  202.          TfpTools fu=new TfpTools();  
  203.          for(FTPFile ff:fs){  
  204.              if(ff.getName().contains(fileName)){  
  205.                  if(fu.ToDetermineWhetherAFileExists(ff.getName())){  
  206.                  File localFile = new File(localPath+“/”+ff.getName());  
  207.                  OutputStream is = new FileOutputStream(localFile);  
  208.                  ftp.retrieveFile(ff.getName(), is);  
  209.                  is.close();  
  210.                  }  
  211.                  }  
  212.          }  
  213.              ftp.logout();  
  214.              success = true;  
  215.         } catch (IOException e) {  
  216.                   e.printStackTrace();  
  217.               } finally {  
  218.                     if (ftp.isConnected()) {  
  219.                         try {  
  220.                              ftp.disconnect();  
  221.                          } catch (IOException ioe) {  
  222.                          }  
  223.                      }  
  224.                 }  
  225.                   return success;  
  226.     }   
  227.       
  228.     public boolean ToDetermineWhetherAFileExists(String fileName){  
  229.         boolean flag=true;  
  230.         Vector<String> v=new Vector<String>();  
  231.         v=GetTestXlsFileName(”c:/JX_jiekou/src/backups”);  
  232.         for(int i=0;i<v.size();i++){  
  233.             String str=(String)v.elementAt(i);  
  234.             if(str.equals(fileName)){  
  235.                 flag=false;  
  236.             }  
  237.         }  
  238.         return flag;  
  239.     }  
  240.     /** 
  241.      * 讀取本地某個目錄下,所有txt文件的文件名 
  242.      * @param fileAbsolutePath        本地文件目錄。 
  243.      * @return 
  244.      */  
  245.     public static Vector<String> GetTestXlsFileName(String fileAbsolutePath) {  
  246.         Vector<String> vecFile = new Vector<String>();  
  247.         File file = new File(fileAbsolutePath);  
  248.         File[] subFile = file.listFiles();  
  249.    
  250.         for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {  
  251.            // 判斷是否爲文件夾   
  252.            if (!subFile[iFileLength].isDirectory()) {  
  253.                String fileName = subFile[iFileLength].getName();  
  254.                // 判斷是否爲.txt結尾   
  255.                 if (fileName.trim().toLowerCase().endsWith(“.txt”)) {  
  256.                    vecFile.add(fileName);  
  257.                 }  
  258.            }  
  259.        }  
  260.         return vecFile;  
  261.    }  
  262.       
  263.     public boolean truncateTable(String tableName){  
  264.         Connection conn=null;  
  265.         Statement sm=null;  
  266.         String sql=”truncate table ”+tableName;  
  267.         try {  
  268.             conn=DBConfig.getConn(JkConfig.getDb_url(),JkConfig.getDb_username(),JkConfig.getDb_password(),0);  
  269.             sm=conn.createStatement();  
  270.             sm.executeUpdate(sql);  
  271.         } catch (Exception e) {  
  272.             e.printStackTrace();  
  273.         }  
  274.     return true;  
  275.     }  
  276.     public void closeConnect() {  
  277.         try {  
  278.             if (ftpClient != null) {  
  279.                 ftpClient.logout();  
  280.                 ftpClient.disconnect();  
  281.                 ftpClient=null;  
  282.             }  
  283.         } catch (Exception e) {  
  284.             e.printStackTrace();  
  285.         }  
  286.     }  
  287. }  
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;



public class TfpTools {
    //連接ftp
    private FTPClient ftpClient = null;
//    public static String ip = "117.21.208.37";
//    public static int port = 21;
//    public static String username = "eftp";
//    public static String password = "e1f2t3p4";
//    public static String sub_path = "/opt/tomcat/webapps/photocdn/msgdata/";
    /**
     * 連接ftp
     */
    public void connectServer(String ip,int port,String username,String password,String sub_path) throws Exception {
        int i = 10;
        if (ftpClient == null) {
            int reply;
            while (i > 0) {
                try {
                    ftpClient = new FTPClient();
                    if (port != 21)
                        ftpClient.connect(ip, port);
                    else
                        ftpClient.connect(ip);
                    ftpClient.login(username, password);
                    reply = ftpClient.getReplyCode();
                    if (!FTPReply.isPositiveCompletion(reply)) {
                        ftpClient.disconnect();
                    }
                    System.out.println("sub_path=============="+sub_path);
                    // 對目錄進行轉換
                    if (ftpClient.changeWorkingDirectory(sub_path)) {
                    } else {
                        ftpClient.disconnect();
                        ftpClient = null;
                    }
                } catch (Exception e) {  
                    e.printStackTrace();
                    if (0 < i--) {
                        try {
                            Thread.sleep(10000);
                            continue;
                        } catch (Exception ex) {
                        }
                    }
                }
                i = 0;
            }
        }
    }
    /**
     * 文件上傳
     * @param ip
     * @param port
     * @param username
     * @param password
     * @param sub_path                遠程文件上傳目錄
     * @param localFilePath              本地文件存放路徑、、
     * @param newFileName            遠程生成的文件路徑和文件名
     * @throws Exception
     */
    public void uploadFile(String ip,int port,String username,String password,String sub_path,String localFilePath, String newFileName)throws Exception {
    BufferedInputStream buffIn = null;
    try {
        connectServer(ip,port,username,password,sub_path);        //連接服務器
        System.out.println("start upload");
        buffIn = new BufferedInputStream(new FileInputStream(localFilePath));
        System.out.println("find localFilePath success");
        ftpClient.storeFile(newFileName, buffIn);
        System.out.println("upload success");
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        try {
            if (buffIn != null)
                buffIn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    }
    /**
     * 
     * Definition: 讀取txt文件,存放到list中,以便於讀取
     * author: xiehaoyu
     * Created date: 2013-6-14
     * @param readTxt
     * @return
     */
    public static List<String> readTxt(String readTxt){
        BufferedReader br = null;
        List<String> list = new ArrayList<String>();
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(    
                    new File(readTxt))));
            String temp = br.readLine();
            while (temp != null) {
                String[] str=temp.toString().trim().split("\\|");
                for(String s : str){
                    if(!"".equals(s))
                    list.add(s);
                }
                temp=br.readLine();
            }
            br.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
         return list;
    }
    public void copyFile(String oldPath, String newPath) {
        try {
          int bytesum = 0;
          int byteread = 0;
          File oldfile = new File(oldPath);
          if (oldfile.exists()) { //文件存在時
            InputStream inStream = new FileInputStream(oldPath); //讀入原文件
            FileOutputStream fs = new FileOutputStream(newPath);
            byte[] buffer = new byte[1444];
            while ( (byteread = inStream.read(buffer)) != -1) {
              bytesum += byteread; //字節數 文件大小
              System.out.println(bytesum);
              fs.write(buffer, 0, byteread);
            }
            inStream.close();
          }
        }
        catch (Exception e) {
          System.out.println("複製單個文件操作出錯");
          e.printStackTrace();

        }

    }

    public void delFile(String filePathAndName) {
        try {
          String filePath = filePathAndName;
          filePath = filePath.toString();
          java.io.File myDelFile = new java.io.File(filePath);
          myDelFile.delete();
        }
        catch (Exception e) {
          System.out.println("刪除文件操作出錯");
          e.printStackTrace();
        }
    }

    /**
     * 文件下載。。
     * @param url                ftp ip
     * @param port                ftp端口
     * @param username            
     * @param password
     * @param remotePath        下載路徑
     * @param fileName            下載文件中包含什麼文件名
     * @param localPath            本地存放路徑
     * @return
     */
    public static boolean downFile(
             String url,
             int port,
             String username,
             String password,
             String remotePath,
             String fileName,
             String localPath){
     boolean success = false;
     FTPClient ftp = new FTPClient();
     try {
         int reply;
         ftp.connect(url, port);
         //如果採用默認端口,可以使用ftp.connect(url)的方式直接連接FTP服務器 
         ftp.login(username, password);//登錄 
         reply = ftp.getReplyCode();
         if (!FTPReply.isPositiveCompletion(reply)) {
         ftp.disconnect();
         return success;
         }
         ftp.changeWorkingDirectory(remotePath);//轉移到FTP服務器目錄
         FTPFile[] fs = ftp.listFiles();
         TfpTools fu=new TfpTools();
         for(FTPFile ff:fs){
             if(ff.getName().contains(fileName)){
                 if(fu.ToDetermineWhetherAFileExists(ff.getName())){
                 File localFile = new File(localPath+"/"+ff.getName());
                 OutputStream is = new FileOutputStream(localFile);
                 ftp.retrieveFile(ff.getName(), is);
                 is.close();
                 }
                 }
         }
             ftp.logout();
             success = true;
        } catch (IOException e) {
                  e.printStackTrace();
              } finally {
                    if (ftp.isConnected()) {
                        try {
                             ftp.disconnect();
                         } catch (IOException ioe) {
                         }
                     }
                }
                  return success;
    } 

    public boolean ToDetermineWhetherAFileExists(String fileName){
        boolean flag=true;
        Vector<String> v=new Vector<String>();
        v=GetTestXlsFileName("c:/JX_jiekou/src/backups");
        for(int i=0;i<v.size();i++){
            String str=(String)v.elementAt(i);
            if(str.equals(fileName)){
                flag=false;
            }
        }
        return flag;
    }
    /**
     * 讀取本地某個目錄下,所有txt文件的文件名
     * @param fileAbsolutePath        本地文件目錄。
     * @return
     */
    public static Vector<String> GetTestXlsFileName(String fileAbsolutePath) {
        Vector<String> vecFile = new Vector<String>();
        File file = new File(fileAbsolutePath);
        File[] subFile = file.listFiles();

        for (int iFileLength = 0; iFileLength < subFile.length; iFileLength++) {
           // 判斷是否爲文件夾 
           if (!subFile[iFileLength].isDirectory()) {
               String fileName = subFile[iFileLength].getName();
               // 判斷是否爲.txt結尾 
                if (fileName.trim().toLowerCase().endsWith(".txt")) {
                   vecFile.add(fileName);
                }
           }
       }
        return vecFile;
   }

    public boolean truncateTable(String tableName){
        Connection conn=null;
        Statement sm=null;
        String sql="truncate table "+tableName;
        try {
            conn=DBConfig.getConn(JkConfig.getDb_url(),JkConfig.getDb_username(),JkConfig.getDb_password(),0);
            sm=conn.createStatement();
            sm.executeUpdate(sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
    return true;
    }
    public void closeConnect() {
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
                ftpClient=null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}


案例二:
案例二:
案例二:
document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js?cdnversion=" + Math.ceil(new Date()/3600000)
    <div id="digg" articleid="24458469">
        <dl id="btnDigg" class="digg digg_disable" onclick="btndigga();">

             <dt>頂</dt>
            <dd>0</dd>
        </dl>


        <dl id="btnBury" class="digg digg_disable" onclick="btnburya();">

              <dt>踩</dt>
            <dd>0</dd>               
        </dl>

    </div>
 <div class="tracking-ad" data-mod="popu_222"><a href="javascript:void(0);" target="_blank">&nbsp;</a>   </div>
<div class="tracking-ad" data-mod="popu_223"> <a href="javascript:void(0);" target="_blank">&nbsp;</a></div>
<script type="text/javascript">
            function btndigga() {
                $(".tracking-ad[data-mod='popu_222'] a").click();
            }
            function btnburya() {
                $(".tracking-ad[data-mod='popu_223'] a").click();
            }
        </script>

<div style="clear:both; height:10px;"></div>


        <div class="similar_article">
                <h4></h4>
                <div class="similar_c" style="margin:20px 0px 0px 0px">
                    <div class="similar_c_t">
                      &nbsp;&nbsp;相關文章推薦
                    </div>

                    <div class="similar_wrap tracking-ad" data-mod="popu_36">                       
                        <ul class="similar_list fl">    
                        </ul>
                          <ul class="similar_list fr">      
                        </ul>
                    </div>
                </div>
            </div>   
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章