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. public class TestFTP {
  4.  
  5.     public static void main(String[] args) {
  6.         try {
  7.             FTPClient ftp = new FTPClient();
  8.             // initialize ftp connection
  9.             /*
  10.              *
  11.              */
  12.  
  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.             // TODO Auto-generated catch block
  30.             e.printStackTrace();
  31.         } catch (IOException e) {
  32.             // TODO Auto-generated catch block
  33.             e.printStackTrace();
  34.         }
  35.     }
  36. }
标签:,


京ICP备05059555号

收藏 & 分享

Powered by 17fav.com