apache提供的FTP功能

apache提供的FTP功能还算强大,最近研究了一下它的断点续传功能,写下我的收获,以供大家参考。

  首先需要引入commons-net-1.4.1.jar包,该包可在http://commons.apache.org/downloads/download_net.cgi下载。

  断点续传的类ContinueFTP如下:

import java.io.*;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
public class ContinueFTP {
  private FTPClient ftpClient = new FTPClient();
  public ContinueFTP() {
    ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
  }
  public boolean connect(String hostname, int port, String username, String password) throws IOException {
    ftpClient.connect(hostname, port);
    if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
      if (ftpClient.login(username, password)) {
        return true;
      }
    }
    disconnect();
    return false;
  }
  public boolean download(String remote, String local) throws IOException {
    ftpClient.enterLocalPassiveMode();
    boolean result;
    File f = new File(local);
    if (f.exists()) {
      OutputStream out = new FileOutputStream(f, true);
      ftpClient.setRestartOffset(f.length());
      result = ftpClient.retrieveFile(remote, out);
      out.close();
    } else {
      OutputStream out = new FileOutputStream(f);
      result = ftpClient.retrieveFile(remote, out);
      out.close();
    }
    return result;
  }
 
  public void disconnect() throws IOException {
    if (ftpClient.isConnected()) {
     ftpClient.disconnect();
    }
  }
 
  public static void main(String[] args){
    ContinueFTP myFtp = new ContinueFTP();
    try {
      myFtp.connect("192.168.0.100", 21, "123", "123");
      myFtp.download("t.txt","G:/test.txt");
      myFtp.disconnect();
    } catch (IOException e) {
      System.out.println("连接FTP出错:"+e.getMessage());
    }
  }
}
 

  上面的main函数是个例子,很容易看明白:
  connect(String hostname, int port, String username, String password)中,各参数依次是主机名或IP,端口号,用户名和密码。
  download(String remote, String local)中,参数分别是远程FTP中的文件名和下载到本地中的文件全路径。

  注意上面的类中用到了PrintCommandListener.java,它是放在commons-net-1.4.1.jar源码的example下的,在commons-net-1.4.1.jar中并没有打进来,这里贴出这个类,如果需要的话和ContinueFTP.java放在一起就行了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值