工作需要使用了org.apache.commons.net.ftp.FTPClient來操作FTP,記錄一下心得。

這個類封裝的很完善,使用起來也很簡單,只是在使用retrieveFileStream的時候碰到了一點小問題,就是不知道怎么完成傳輸狀態,嘗試發送abor指令也不行。查看了源代碼之后看到這一段說明以后解決問題:

* You must close the InputStream when you
* finish reading from it. The InputStream itself will take care of
* closing the parent data connection socket upon being closed. To
* finalize the file transfer you must call
* {@link #completePendingCommand completePendingCommand } and
* check its return value to verify success.

代碼如下:

import org.apache.commons.net.ftp.FTPClient; 
  
public class TestFTP 
  
    
public static void main(String[] args) 
        
try 
            FTPClient ftp 
= new FTPClient(); 
            
// initialize ftp connection 
            /* 
             * 
             
*/
 
  
            String remotefile 
= "test.xml"
            InputStream is 
= null
  
            is 
= ftp.retrieveFileStream(remotefile); 
  
            
if (is != null
                is.close(); 
            }
 
  
            
if (!ftp.completePendingCommand()) 
                ftp.logout(); 
                ftp.disconnect(); 
            }
 
            
            
// continue 
        }
 catch (SocketException e) 
            
// TODO Auto-generated catch block 
            e.printStackTrace(); 
        }
 catch (IOException e) 
            
// TODO Auto-generated catch block 
            e.printStackTrace(); 
        }
 
    }
 
}