快捷搜索:   服务器  安全  linux 安全  MYSQL  dedecms

FTPClient中 retrieveFileStream 的用法

工作需要使用了org.apache.commons.net.ftp.FTPClient来操作FTP,记录一下心得。

 

    这个类封装的很完善,使用起来也很简单,只是在使用retrieveFileStream的时候碰到了一点小问题,就是不知道怎么完成传输状态,尝试发送abor指令也不行。在咨询了bianbian和查看了源代码之后看到这一段说明以后解决问题:

 

/*
* 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.
*/

 

代码如下:

 

  1. import org.apache.commons.net.ftp.FTPClient;  
  2.  
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.net.SocketException;  
  6.  
  7. public class TestFTP {  
  8.  
  9.     public static void main(String[] args) {  
  10.         try {  
  11.             FTPClient ftp = new FTPClient();  
  12.             // initialize ftp connection  
  13.             String remotefile = "test.xml";  
  14.             InputStream is = null;  
  15.  
  16.             is = ftp.retrieveFileStream(remotefile);  
  17.  
  18.             if (is != null) {  
  19.                 is.close();  
  20.             }  
  21.  
  22.             if (!ftp.completePendingCommand()) {  
  23.                 ftp.logout();  
  24.                 ftp.disconnect();  
  25.             }  
  26.  
  27.             // continue  
  28.         } catch (SocketException e) {  
  29.             e.printStackTrace();  
  30.         } catch (IOException e) {  
  31.             e.printStackTrace();  
  32.         }  
  33.     }  
  34. }  

 

顶(1)
踩(0)

您可能还会对下面的文章感兴趣:

最新评论