您的位置:首页 > 编程语言 > Java开发

JAVA FTP文件下载完美版

2018-01-31 11:17 393 查看
之前在项目上遇到FTP下载(也是从别的文章上弄过来的,忘了从那弄的了,抱歉)的问题,文件名中文太长,文件名中有空格(红色为修改后的代码)。修改后的代码如下:

public class FtpUtil {
private Logger logger = Logger.getLogger(this.getClass());
/**
* 获取FTPClient对象
*
* @param ftpHost
*            FTP主机服务器
* @param ftpPassword
*            FTP 登录密码
* @param ftpUserName
*            FTP登录用户名
* @param ftpPort
*            FTP端口 默认为21
* @return
*/
public FTPClient getFTPClient(String ftpHost, String ftpUserName,
String ftpPassword, int ftpPort) {
FTPClient ftpClient = new FTPClient();
try {
ftpClient = new FTPClient();
ftpClient.connect(ftpHost, ftpPort);// 连接FTP服务器
ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
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;
}

/*
* 从FTP服务器下载文件
*
* @param ftpHost FTP IP地址
*
* @param ftpUserName FTP 用户名
*
* @param ftpPassword FTP用户名密码
*
* @param ftpPort FTP端口
*
* @param ftpPath FTP服务器中文件所在路径 格式: ftptest/aa
*
* @param localPath 下载到本地的位置 格式:H:/download
*
* @param fileName 文件名称
*/
public String downloadFtpFile(String ftpHost, String ftpUserName,
String ftpPassword, int ftpPort, String ftpPath, String localPath,
String fileName) {

FTPClient ftpClient = null;

try {
 String remoteFileName = java.net.URLDecoder.decode(fileName, "utf-8");
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.replace(" ",""));
OutputStream os = new FileOutputStream(localFile);
ftpClient.retrieveFile(new String(remoteFileName.getBytes("GBK"),"ISO-8859-1"), os);
os.close();
ftpClient.logout();
return "1";
} catch (FileNotFoundException e) {
logger.error("没有找到" + ftpPath + "文件");
e.printStackTrace();
return "2";
} catch (SocketException e) {
logger.error("连接FTP失败.");
e.printStackTrace();
return "3";
} catch (IOException e) {
e.printStackTrace();
logger.error("文件读取错误。");
return "4";
}

}

}


如有侵权请联系删除
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ftp JAVA文件下载