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放在一起就行了