class="java" name="code">
package com.test.ftp.download;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
/**
* 使用 FTP 实现文件上传下载<br>
* @author admin
*
*/
public class FavFTPUtil {
public static Logger _log = Logger.getLogger(FavFTPUtil.class);
/**
* 下载文件
*
* @param hostname
* FTP服务器地址
* @param port
* FTP服务器端口号
* @param username
* FTP登录帐号
* @param password
* FTP登录密码
* @param pathname
* FTP服务器文件目录
* @param filename
* 文件名称
* @param localPath
* 下载后的文件路径
* @return
*/
public static boolean downloadFile(String hostname, int port, String username, String password, String pathname,
String filename, String localPath) {
boolean flag = false;
FTPClient ftpClient = new FTPClient();
//传输的字符编码(防乱码)
ftpClient.setControlEncoding("UTF-8");
//超时时间(防止FTP僵死)
ftpClient.setConnectTimeout(1000 * 60);
ftpClient.setDataTimeout(1000 * 60);
ftpClient.setDefaultTimeout(1000 * 60);
//工作流的大小
ftpClient.setBufferSize(1024 * 4);
// 被动模式
ftpClient.enterLocalPassiveMode();
try {
// 连接FTP服务器
ftpClient.connect(hostname, port);
// 登录FTP服务器
ftpClient.login(username, password);
// 验证FTP服务器是否登录成功
int replyCode = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(replyCode)) {
_log.error("Failed to login");
return flag;
}
// 切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
FTPFile[] ftpFiles = ftpClient.listFiles();
_log.info("File number:" + ftpFiles.length);
for (FTPFile file : ftpFiles) {
if (filename.equalsIgnoreCase(file.getName())) {
File localFile = new File(localPath + "/" + file.getName());
OutputStream os = new FileOutputStream(localFile);
_log.info("begin to download file ------------------");
ftpClient.retrieveFile(file.getName(), os);
_log.info("finished !!!");
os.close();
}
}
ftpClient.logout();
flag = true;
} catch (Exception e) {
_log.error(e);
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.logout();
} catch (IOException e) {
}
}
}
return flag;
}
public static void main(String[] args) {
// FTP server account info
String hostname = "192.168.1.2";
int port = 21;
String username = "test";
String password = "abc";
// download file info in FTP server
String pathname = "filePath";
String filename = "file.zip";
// location for downloaded file in local
String localpath = "C:/Data";
downloadFile(hostname, port, username, password, pathname, filename, localpath);
}
}
开发过程中遇到一个问题,一开始server连接成功了,server上文件路径也没有问题,可是ftpClient.listFiles()始终返回empty,后来加上
ftpClient.enterLocalPassiveMode();后才执行成功了。
参考:
https://blog.csdn.net/cainiao_ACCP/article/details/71394891