一:下载commons-net-1.4.1.jar包,放到lib下,并加载到.classpath文件中
二:编写工具类FtpUtil.Java如下
- package common;
-
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.net.SocketException;
- import java.util.Properties;
- import org.apache.log4j.Logger;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.apache.commons.net.ftp.*;
-
-
- public class FtpUtil {
-
- private final static Log logger = LogFactory.getLog(FtpUtil.class);
-
-
- public static FTPClient getFTPClient(String ftpHost, String ftpUserName,
- String ftpPassword, int ftpPort) {
- FTPClient ftpClient = new FTPClient();
- try {
- ftpClient = new FTPClient();
- ftpClient.connect(ftpHost, ftpPort);
- ftpClient.login(ftpUserName, ftpPassword);
- if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
- logger.info("未连接到FTP,用户名或密码错误。");
- ftpClient.disconnect();
- } else {
- logger.info("FTP连接成功。");
- }
- } catch (SocketException e) {
- e.printStackTrace();
- logger.info("FTP的IP地址可能错误,请正确配置。");
- } catch (IOException e) {
- e.printStackTrace();
- logger.info("FTP的端口错误,请正确配置。");
- }
- return ftpClient;
- }
-
-
- public static void downloadFtpFile(String ftpHost, String ftpUserName,
- String ftpPassword, int ftpPort, String ftpPath, String localPath,
- String fileName) {
-
- FTPClient ftpClient = null;
-
- try {
- ftpClient = getFTPClient(ftpHost, ftpUserName, ftpPassword, ftpPort);
- ftpClient.setControlEncoding("UTF-8");
- ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
- ftpClient.enterLocalPassiveMode();
- ftpClient.changeWorkingDirectory(ftpPath);
-
- File localFile = new File(localPath + File.separatorChar + fileName);
- OutputStream os = new FileOutputStream(localFile);
- ftpClient.retrieveFile(fileName, os);
- os.close();
- ftpClient.logout();
-
- } catch (FileNotFoundException e) {
- logger.error("没有找到" + ftpPath + "文件");
- e.printStackTrace();
- } catch (SocketException e) {
- logger.error("连接FTP失败.");
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- logger.error("文件读取错误。");
- e.printStackTrace();
- }
-
- }
-
-
-
- }
三、测试代码
假设已经存在一个FTP服务器,登录的用户名和密码为zyf,端口为22,登后的家目录下进入ftpdir目录,下面有一个11.txt文件用于下载测试
- package scripts.testscript;
-
- import org.testng.annotations.Test;
-
- import common.FtpUtil;
-
- public class FtpDownloadTestScript {
- @Test
- public void run() {
-
- String ftpHost = "192.168.26.132";
- String ftpUserName = "zyf";
- String ftpPassword = "zyf";
- int ftpPort = 21;
- String ftpPath = "ftpdir/";
- String localPath = "H:/download";
- String fileName = "11.txt";
- FtpUtil.downloadFtpFile(ftpHost, ftpUserName, ftpPassword, ftpPort, ftpPath, localPath, fileName);
- }
- }
Java代码实现FTP单个文件下载(二)
原文:http://www.cnblogs.com/gaoxuewei/p/6646689.html