# 需求:
将本地文件上传到ftp服务器上指定目录下。
# 代码实现:
```java
import com.smy.framework.base.BaseEntity;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class FtpUtil {
private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);
private static String LOCAL_CHARSET = "GBK";
private static String SERVER_CHARSET = "ISO-8859-1";
/**
* 必填:ip, port, user, password, localFilePathName, remoteFileName
*
* @param uploadDto
*/
public static void upload(FtpDto uploadDto) throws IOException {
if (null == uploadDto) {
throw new ServiceException(CommonErrorCode.NULL_PROPERTIES, new String[] { "uploadDto" });
}
if (StringUtils.isBlank(uploadDto.getIp())) {
throw new ServiceException(CommonErrorCode.NULL_PROPERTIES, new String[] { "uploadDto.ip" });
}
if (StringUtils.isBlank(uploadDto.getPassword())) {
throw new ServiceException(CommonErrorCode.NULL_PROPERTIES, new String[] { "uploadDto.password" });
}
if (0 == uploadDto.getPort()) {
throw new ServiceException(CommonErrorCode.NULL_PROPERTIES, new String[] { "uploadDto.port" });
}
if (StringUtils.isBlank(uploadDto.getUser())) {
throw new ServiceException(CommonErrorCode.NULL_PROPERTIES, new String[] { "uploadDto.user" });
}
if (StringUtils.isBlank(uploadDto.getLocalFilePathName())) {
throw new ServiceException(CommonErrorCode.NULL_PROPERTIES, new String[] { "uploadDto.localFilePathName" });
}
if (StringUtils.isBlank(uploadDto.getRemoteFileName())) {
throw new ServiceException(CommonErrorCode.NULL_PROPERTIES, new String[] { "uploadDto.remoteFileName" });
}
FTPClient ftpClient = new FTPClient();
FileInputStream input = null;
try {
ftpClient.connect(uploadDto.getIp(), uploadDto.getPort());
if(!ftpClient.login(uploadDto.getUser(), uploadDto.getPassword())){
logger.error("[数据提取]-----远程连接服务器账户密码错误:账号-{},密码-{}", uploadDto.getUser(),uploadDto.getPassword());
}
if (!StringUtils.isBlank(uploadDto.getRemoteDir())) {
ftpClient.changeWorkingDirectory(uploadDto.getRemoteDir());
}
//如果目录不存在则创建一个目录
File dir = new File(uploadDto.getRemoteDir());
if(!dir.exists()){
dir.mkdirs();
}
input = new FileInputStream(uploadDto.getLocalFilePathName());
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.storeFile(new String(uploadDto.getRemoteFileName().getBytes("GBK"),"iso-8859-1"),input);
logger.info("上传文件【{}】成功", uploadDto.getLocalFilePathName());
} catch (Exception e) {
logger.error("上传文件失败,参数:{}", uploadDto, e);
throw new ServiceException(CommonErrorCode.ERROR_FILE_UPLOAD, e, new String[] { uploadDto.getLocalFilePathName() });
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.logout();
}
} catch (Exception e) {
logger.warn("关闭ftp连接失败!");
}
}
if (null != input) {
try {
input.close();
} catch (IOException e) {
}
}
}
public static FtpDto initFtpDto() {
try {
return (FtpDto) Class.forName(getClassName() + "$FtpDto").newInstance();
} catch (Exception e) {
throw new RuntimeException("init FtpDto error", e);
}
}
private static String getClassName() {
return new Object() {
public String getClassName() {
String clazzName = this.getClass().getName();
return clazzName.substring(0, clazzName.lastIndexOf('$'));
}
}.getClassName();
}
public static class FtpDto extends BaseEntity {
/**
*
*/
private static final long serialVersionUID = 2610830652396624141L;
/**
* ip
*/
private String ip;
private int port = 21;
private String user;
private String password;
private String remoteDir;
private String localFilePathName;
private String remoteFileName;
private String proxyHost;
private int proxyPort;
public FtpDto() {
}
/**
* ip地址
*
*/
public String getIp() {
return ip;
}
/**
* ip地址
*
* @param ip
*/
public void setIp(String ip) {
this.ip = ip;
}
/**
* port端口
*
*/
public int getPort() {
return port;
}
/**
* port端口
*
* @param port
*/
public void setPort(int port) {
this.port = port;
}
/**
* user用户名
*
*/
public String getUser() {
return user;
}
/**
* user用户名
*
* @param user
*/
public void setUser(String user) {
this.user = user;
}
/**
* password密码
*
*/
public String getPassword() {
return password;
}
/**
* password密码
*
* @param password
*/
public void setPassword(String password) {
this.password = password;
}
/**
* remoteDir FTP远程目录
*
*/
public String getRemoteDir() {
return remoteDir;
}
/**
* remoteDir FTP远程目录
*
* @param remoteDir
*/
public void setRemoteDir(String remoteDir) {
this.remoteDir = remoteDir;
}
/**
* localFilePathName 上传的文件文件名(包括路径)
*
*/
public String getLocalFilePathName() {
return localFilePathName;
}
/**
* localFilePathName 上传的文件文件名(包括路径)
*
* @param localFilePathName
*/
public void setLocalFilePathName(String localFilePathName) {
this.localFilePathName = localFilePathName;
}
/**
* remoteFileName 上传后的文件文件名
*
*/
public String getRemoteFileName() {
return remoteFileName;
}
/**
* remoteFileName 上传后的文件文件名
*
* @param remoteFileName
*/
public void setRemoteFileName(String remoteFileName) {
this.remoteFileName = remoteFileName;
}
/**
* proxyHost 代理的主机
*
*/
public String getProxyHost() {
return proxyHost;
}
/**
* proxyHost 代理的主机
*
* @param proxyHost
*/
public void setProxyHost(String proxyHost) {
this.proxyHost = proxyHost;
}
/**
* proxyPort 代理的端口
*
*/
public int getProxyPort() {
return proxyPort;
}
/**
* proxyPort 代理的端口
*
* @param proxyPort
*/
public void setProxyPort(int proxyPort) {
this.proxyPort = proxyPort;
}
}
public static void main(String[] args) {
FtpDto ftpDto = new FtpUtil.FtpDto();
/*
* ftpDto.setIp("ftp2.99bill.com"); ftpDto.setPort(21);
* ftpDto.setUser("smy02"); ftpDto.setPassword("3LwU4nn72y6F");
* //ftpDto.setRemoteDir("data");
* ftpDto.setRemoteFileName("99BILL-SMY-QP-2015-09-09_2015-09-09.zip");
* ftpDto
* .setLocalFilePathName("d:/99BILL-SMY-QP-2015-09-09_2015-09-09.zip");
*/
ftpDto.setIp("172.16.2.127");
ftpDto.setPort(21);
ftpDto.setUser("zhangsan");
ftpDto.setPassword("zhangsan1");
ftpDto.setRemoteDir("/home/zhangsan");
ftpDto.setRemoteFileName("催收全量表1.zip");
ftpDto.setLocalFilePathName("D:\\home\\coreapp\\bdp\\dts-wgq-test02-sheet120200707-165827.zip");
try {
FtpUtil.upload(ftpDto);
} catch (IOException e) {
e.printStackTrace();
}
//ftpDto.setLocalFilePathName("d:/2.gz");
// FtpUtil.download(ftpDto);
/*
* FTPClient ftpClient = new FTPClient(); try {
* ftpClient.connect("139.219.10.106",21); ftpClient.login("hrbb_smy",
* "smy@456"); ftpClient.changeWorkingDirectory("/down");
*
* String dir = "d:/"; String fileName = "smytest.zip";
* ftpClient.storeFile(fileName, new FileInputStream(dir+fileName));
*
* ftpClient.logout(); logger.info("success"); } catch (IOException e) {
* e.printStackTrace(); throw new RuntimeException("FTP客户端出错!", e); }
* finally { try { ftpClient.disconnect(); } catch (IOException e) {
* e.printStackTrace(); throw new RuntimeException("关闭FTP连接发生异常!", e); }
* }
*/
}
}
```