properties配置文件设置:
host=ip
port=21
username=root
password=root
配置文件获取:
InputStream inputStream = FtpUploadUtil.class.getClassLoader()
.getResourceAsStream("uploadfile.properties");
Properties properties = new Properties();
properties.load(inputStream);
Map<String, String> parmMap = new HashMap<String, String>();
parmMap.put("host", properties.getProperty("host"));
parmMap.put("port", properties.getProperty("port"));
parmMap.put("username", properties.getProperty("username"));
parmMap.put("password", properties.getProperty("password"));
1.获取线上文件url
url为下载路径 filePath为存储到本地的文件路径
public static File getFile(String url, String filePath) {
File file = null;
URL urlfile;
try {
// 创建一个临时路径
file = new File(filePath);
//下载
urlfile = new URL(url);
try{
InputStream inStream = urlfile .openStream();
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
inStream.close();
}catch (IOException e) {
Logger.error("创建失败!");
}
} catch (Exception e) {
Logger.error("创建临时文件出错:-》{}"+e.getMessage());
}
return file;
}
也可直接将本地文件上传至FTP服务器中,当然实际项目业务场景多为获取线上文件
2、文件上传至FTP服务器
destPath为服务器文件夹路径,如没有会自动创建
public void ftpUploadFile(Map<String, String> parm,String uploadFilePath,String destPath) throws BusinessException{
String hostname = parm.get("host");
int port = new Integer(parm.get("port"));
String username = parm.get("username");
String password = parm.get("password");
FTPClient ftp = new FTPClient();
Logger.info("准备连接到ftp");
try {
//连接
ftp.connect(hostname, port);
//登录
boolean loginS = ftp.login(username, password);
if (!loginS) {
throw new BusinessException("ftp登录失败,用户名或密码错误");
}else{
Logger.info("ftp登录成功");
}
// 获取本地文件并上传
String file = uploadFilePath;
FileInputStream input = new FileInputStream(file);
//切换到工作目录
if (!ftp.changeWorkingDirectory(destPath)) {
ftp.changeWorkingDirectory("/");
String[] dirs = destPath.split("/");
for (String dir : dirs) {
ftp.makeDirectory(dir);
ftp.changeWorkingDirectory(dir);
}
}
//必须要设置以二进制的方式传输文件
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
//被动模式
ftp.enterLocalPassiveMode();
file = new String(file.getBytes("GBK"),"iso-8859-1");
if (!ftp.storeFile(new File(file).getName(), input)) {
throw new BusinessException("失败,服务器返回:" + ftp.getReplyString());
} else {
Logger.info("文件:" + new File(file).getName() + " 上传成功");
}
input.close();
ftp.logout();
} catch (IOException e) {
ExceptionUtils.wrappException(e);
}
}
3、测试demo
String filepath = "localpath"; String destpath = "file/0810";
String downurl = "https://trustedsign.com/kxqtest/common/download/MNBCLKYBUNTEOYYK";
File file = getFile(downurl,filepath);
ftpUploadFile(host,port,username,password,file.getPath(),destpath);
4、总结
该案例是项目过程中遇到的,比较有参考意义,如有疑问请及时留言,多多交流