import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSON;
public class FtpUtils {
private static Logger log = LoggerFactory.getLogger(FtpUtils.class);
/**
* FtpConfig sourceConfig = new FtpConfig("ftp地址",端口,"账号","密码");
FtpConfig targetConfig = new FtpConfig("ftp地址",端口,"账号","密码");
*/
public static final int ftpPost = 21;
public static final int service51Post = 4088;
//访问图片的域名
public static final String domainName = "图片访问域名";
public static final String service51host = "ftp所在服务器地址";
public static final String service51UserName = "ftp所在服务器的账号";
public static final String service51Password = "密码";
private static final String lqservice36host = "另一台ftp服务器地址";
private static final String lqservice36UserName = "账号";
private static final String lqservice36Password = "密码";
/**
* 上传文件
* @param pathname ftp服务保存地址
* @param fileName 上传到ftp的文件名
* @param originfilename 待上传文件的名称(绝对地址) *
* @return
*/
public boolean uploadFile( String pathname, String originfilename, FTPClient ftpClient){
boolean flag = false;
InputStream inputStream = null;
try{
log.info(">>>>>开始上传文件>>>>>>");
File file = new File(originfilename);
inputStream = new FileInputStream(file);
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname,ftpClient);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.storeFile(file.getName(), inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
log.info(">>>>>上传文件成功>>>>>>");
}catch (Exception e) {
log.error(">>>>>上传文件失败>>>>>> {}", e);
// e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
// e.printStackTrace();
log.error("error {}", e);
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
// e.printStackTrace();
log.error("error {}", e);
}
}
}
return true;
}
//改变目录路径
public static boolean changeWorkingDirectory(String directory, FTPClient ftpClient) {
boolean flag = true;
try {
flag = ftpClient.changeWorkingDirectory(directory);
if (flag) {
log.info("进入文件夹" + directory + " 成功!");
} else {
log.info("进入文件夹" + directory + " 失败!开始创建文件夹");
}
} catch (IOException e) {
// e.printStackTrace();
log.error("error {}", e);
}
return flag;
}
//创建多层目录文件,如果有ftp服务器已存在该文件,则不创建,如果无,则创建
public static boolean CreateDirecroty(String remote, FTPClient ftpClient) throws IOException {
boolean success = true;
String directory = remote + "/";
// 如果远程目录不存在,则递归创建远程服务器目录
if (!directory.equalsIgnoreCase("/") && !changeWorkingDirectory(new String(directory),ftpClient)) {
int start = 0;
int end = 0;
if (directory.startsWith("/")) {
start = 1;
} else {
start = 0;
}
end = directory.indexOf("/", start);
String path = "";
String paths = "";
while (true) {
String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
path = path + "/" + subDirectory;
if (!existFile(path,ftpClient)) {
if (makeDirectory(subDirectory,ftpClient)) {
changeWorkingDirectory(subDirectory,ftpClient);
} else {
log.info("创建目录[" + subDirectory + "]失败");
changeWorkingDirectory(subDirectory,ftpClient);
}
} else {
changeWorkingDirectory(subDirectory,ftpClient);
}
paths = paths + "/" + subDirectory;
start = end + 1;
end = directory.indexOf("/", start);
// 检查所有目录是否创建完毕
if (end <= start) {
break;
}
}
}
return success;
}
//判断ftp服务器文件是否存在
public static boolean existFile(String path, FTPClient ftpClient) throws IOException {
boolean flag = false;
FTPFile[] ftpFileArr = ftpClient.listFiles(path);
if (ftpFileArr.length > 0) {
flag = true;
}
return flag;
}
//创建目录
public static boolean makeDirectory(String dir, FTPClient ftpClient) {
boolean flag = true;
try {
flag = ftpClient.makeDirectory(dir);
if (flag) {
log.info("创建文件夹" + dir + " 成功!");
} else {
log.info("创建文件夹" + dir + " 失败!");
}
} catch (Exception e) {
// e.printStackTrace();
log.error("error {}", e);
}
return flag;
}
/** * 下载文件 *
* @param pathname FTP服务器文件目录 *
* @param filename 文件名称 *
* @param localpath 下载后的文件路径 *
* @return */
public boolean downloadFile(String pathname, String localpath, FTPClient ftpClient){
boolean flag = false;
OutputStream os=null;
try {
log.info("开始下载文件");
//切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
FTPFile[] ftpFiles = ftpClient.listFiles();
for(FTPFile file : ftpFiles){
File localFile = new File(localpath + "/" + file.getName());
os = new FileOutputStream(localFile);
ftpClient.retrieveFile(file.getName(), os);
os.close();
}
ftpClient.logout();
flag = true;
log.info("下载文件成功");
} catch (Exception e) {
log.error("下载文件失败error {}", e);
// e.printStackTrace();
} finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
// e.printStackTrace();
log.error("error {}", e);
}
}
if(null != os){
try {
os.close();
} catch (IOException e) {
// e.printStackTrace();
log.error("error {}", e);
}
}
}
return flag;
}
/** * 删除文件 *
* @param pathname FTP服务器保存目录 *
* @param filename 要删除的文件名称 *
* @return */
public boolean deleteFile(String pathname, String filename, FTPClient ftpClient){
boolean flag = false;
try {
log.info("开始删除文件");
//切换FTP目录
ftpClient.changeWorkingDirectory(pathname);
ftpClient.dele(filename);
ftpClient.logout();
flag = true;
log.info("删除文件成功");
} catch (Exception e) {
log.error("删除文件失败error {}", e);
// e.printStackTrace();
} finally {
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
// e.printStackTrace();
log.error("error {}", e);
}
}
}
return flag;
}
public FileOutputStream getOutputStream(FTPClient ftpClient, String localBaseDir, String remoteFilePath) throws Exception {
FileOutputStream outputStream = new FileOutputStream(localBaseDir + remoteFilePath);
ftpClient.enterLocalPassiveMode();
ftpClient.retrieveFile(remoteFilePath, outputStream);
return outputStream;
}
public void startDownFile(FTPClient ftpClient, String localBaseDir, String remoteFilePath) throws Exception {
if (ftpClient != null) {
try {
FileOutputStream outputStream = new FileOutputStream(localBaseDir + remoteFilePath);
ftpClient.enterLocalPassiveMode();
ftpClient.retrieveFile(remoteFilePath, outputStream);
outputStream.flush();
outputStream.close();
} catch (Exception e) {
// e.printStackTrace();
log.error("error {}", e);
}
} else {
log.info("连接FTP服务器失败");
}
}
/**
* 上传文件
* @param pathname ftp服务保存地址
* @param fileName 上传到ftp的文件名
* @param inputStream 输入文件流
* @return
*/
public static boolean uploadFile(String pathname, String fileName,InputStream inputStream, FTPClient ftpClient){
boolean flag = false;
try{
ftpClient.setFileType(ftpClient.BINARY_FILE_TYPE);
CreateDirecroty(pathname,ftpClient);
ftpClient.makeDirectory(pathname);
ftpClient.changeWorkingDirectory(pathname);
ftpClient.storeFile(fileName, inputStream);
inputStream.close();
ftpClient.logout();
flag = true;
log.info(">>>>>上传文件成功>>>>>>" + pathname + "/"+fileName );
}catch (Exception e) {
log.error(">>>>>上传文件失败>>>>>>error {}", e);
// e.printStackTrace();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOException e){
// e.printStackTrace();
log.error("error {}", e);
}
}
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
// e.printStackTrace();
log.error("error {}", e);
}
}
}
return true;
}
/**
*
* @param filePath //圖片路徑
* @param sourceFtp//圖片所在的ftp服務器
* @param targetFtp//要推榮的服務器
* @return
* @throws Exception
*/
public static String push(String filePath) throws Exception {
log.info("需要推送的图片地址:" + filePath);
if (StringUtils.isEmpty(filePath)) {
return "";
}
InputStream inputStream = null;
FtpConfig sourceConfig = new FtpConfig(lqservice36host,ftpPost,lqservice36UserName,lqservice36Password);
FtpConfig targetConfig = new FtpConfig(service51host,service51Post,service51UserName,service51Password);
if (sourceConfig.getFtpClient() == null) {
log.error(">>>>>>>>警告!連接 某某 ftp服務器失敗>>>>>>>>");
return "";
}
if (targetConfig.getFtpClient() == null) {
log.error(">>>>>>>>警告!連接 某某 ftp服務器失敗>>>>>>>>");
return "";
}
FTPClient sourceFtp = sourceConfig.getFtpClient();
FTPClient targetFtp = targetConfig.getFtpClient();
try {
sourceFtp.enterLocalPassiveMode();
targetFtp.enterLocalPassiveMode();
sourceFtp.setDataTimeout(6000);
targetFtp.setDataTimeout(6000);
// 设置文件类型为二进制,与ASCII有区别
sourceFtp.setFileType(FTP.BINARY_FILE_TYPE);
// 设置编码格式
sourceFtp.setControlEncoding("GBK");
// 提取绝对地址的目录以及文件名
filePath = filePath.replace("ftp://"+lqservice36host+":"+ftpPost+"/", "");
filePath = filePath.replace("FTP://"+lqservice36host+":"+ftpPost+"/", "");
String dir = filePath.substring(0, filePath.lastIndexOf("/"));
String file = filePath.substring(filePath.lastIndexOf("/")+1);
// 进入文件所在目录,注意编码格式,以能够正确识别中文目录
sourceFtp.changeWorkingDirectory(new String(dir.getBytes("GBK"),FTP.DEFAULT_CONTROL_ENCODING));
// 检验文件是否存在
inputStream = sourceFtp.retrieveFileStream(new String(file.getBytes("GBK"),FTP.DEFAULT_CONTROL_ENCODING));
try{
if (inputStream != null) {
targetFtp.setFileType(FTP.BINARY_FILE_TYPE);
CreateDirecroty(dir,targetFtp);
targetFtp.changeWorkingDirectory(dir);
targetFtp.storeFile(file, inputStream);
inputStream.close();
targetFtp.logout();
log.info(">>>>>上传文件成功>>>>>>");
}else {
log.error(">>>>>>>文件["+filePath+"]不存在>>>>>>>");
return "";
}
}catch (Exception e) {
log.error(">>>>>上传文件失败>>>>>>error {}", e);
// e.printStackTrace();
}
String hostname = targetConfig.getHostname();
Integer port = targetConfig.getPort();
return domainName + filePath;
} catch (Exception e) {
log.error(">>>>>>>>>>推送文件到ftp服務器上出問題啦!error{}", e);
// e.printStackTrace();
}finally{
//關閉流
if(null != inputStream){
try {
inputStream.close();
} catch (IOException e) {
// e.printStackTrace();
log.error("error {}", e);
}
}
//關閉連接
if(sourceFtp.isConnected()){
try{
sourceFtp.disconnect();
}catch(IOException e){
log.error("關閉源ftp連接異常 error {}", e);
// e.printStackTrace();
}
}
if(targetFtp.isConnected()){
try{
targetFtp.disconnect();
}catch(IOException e){
log.error("關閉目標ftp連接異常error {}", e);
// e.printStackTrace();
}
}
}
return "";
}
public static void main(String[] args) throws Exception {
try {
FtpUtils ftp =new FtpUtils();
List<String> imgList = ftp.imgList();
for (String string : imgList) {
String push = ftp.push(string);
System.out.println("ok" + "," + JSON.toJSONString(push));
}
} catch (Exception e) {
log.error("error {}", e);
}
}
private List<String> imgList(){
List<String> list = new ArrayList<>();
list.add("FTP://ftp服务器地址:21/upload/unicode/20180323/20136271263231521784805270.jpg");
list.add("FTP://ftp服务器地:21/upload/unicode/20180323/20140285545771521781926348.jpg");
list.add("FTP://ftp服务器地:21/upload/unicode/20170516/20102324930511494901996495.jpg");
list.add("FTP://ftp服务器地:21/upload/unicode/20170602/20100952353581496396432773.jpg");
return list;
}
}
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FtpConfig {
private static Logger log = LoggerFactory.getLogger(FtpConfig.class);
//ftp服务器地址
public String hostname;
//ftp服务器端口号默认为21
public Integer port;
//ftp登录账号
public String username;
//ftp登录密码
public String password;
public FTPClient ftpClient;
public FtpConfig (String hostname,Integer port,String username,String password) {
/**
* 初始化ftp服务器
*/
FTPClient ftpClient = new FTPClient();
ftpClient.setControlEncoding("utf-8");
try {
log.info("connecting...ftp服务器:" + hostname + ":" + port);
ftpClient.connect(hostname, port); //连接ftp服务器
ftpClient.login(username, password); //登录ftp服务器
int replyCode = ftpClient.getReplyCode(); //是否成功登录服务器
if(!FTPReply.isPositiveCompletion(replyCode)){
log.info("connect failed...ftp服务器:" + hostname + ":" + port);
}
log.info("connect successfu...ftp服务器:" + hostname + ":" + port);
this.ftpClient = ftpClient;
this.hostname = hostname;
this.port = port;
this.username = username;
this.password = password;
}catch (MalformedURLException e) {
// e.printStackTrace();
log.error("error {}", e);
}catch (IOException e) {
// e.printStackTrace();
log.error("error {}", e);
}
}
public String getHostname() {
return hostname;
}
public void setHostname(String hostname) {
this.hostname = hostname;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public FTPClient getFtpClient() {
return ftpClient;
}
public void setFtpClient(FTPClient ftpClient) {
this.ftpClient = ftpClient;
}
}