`
vakin.jiang
  • 浏览: 147537 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

用org.apache.commons.net.ftp.FTPClient包实现简单文件下载

    博客分类:
  • J2EE
阅读更多
package com.vakinge.ftp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

public class ClientFtpApp {

	private String ip = "localhost";
	private int port = 21;
	private String username = "ftpuser";
	private String password = "123456";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		ClientFtpApp ftp = new ClientFtpApp();
		ftp.downLoadFile("c:\\", "./web/", "Member.asp");
	}

	public void downLoadFile(String localPath, String remotePath, String fileName) {
		FTPFile[] files = null;
		FTPClient client = null;
		try {
			int reply;
			if (client == null) {
				try {
					client = new FTPClient();
					client.setControlEncoding("utf-8");
					client.setDefaultPort(port);
					client.connect(ip, port);
					client.login(username, password);
					reply = client.getReplyCode();
					client.setDataTimeout(120000);
					System.out.println(ip + " 连接成功");
					if (!FTPReply.isPositiveCompletion(reply)) {
						client.disconnect();
						System.out.println(ip + " connect refused!");
					}
				} catch (SocketException e) {
					e.printStackTrace();
					System.out.println(ip + " 连接超时!");
				} catch (IOException e) {
					e.printStackTrace();
					System.out.println(ip + " 服务器无法打开!");
				}
			}

			client.changeWorkingDirectory(remotePath);
			files = client.listFiles();
			for (FTPFile f : files) {
				if (f.getName().equals(fileName)) {
					File localFile = new File(localPath + File.separator
							+ fileName);
					FileOutputStream fos = new FileOutputStream(localFile);
					client.retrieveFile(fileName, fos);
					fos.close();
				}
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (client != null) {
				try {
					client.logout();
					client.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}



随便推荐一个下载jar的网站:http://www.springsource.com/repository/app/
  • lib.rar (211.5 KB)
  • 下载次数: 397
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics