package com.ws.smpweb.common.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
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 org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FTPUtil {
private static final Logger logger = LoggerFactory.getLogger(FTPUtil.class);
private static final int BYTE_SIZE = 1024;
/**
* ftp服务器地址
*/
private String host;
/**
* ftp端口
*/
private int port;
/**
* ftp用户名
*/
private String userName;
/**
* ftp用户
*/
private String password;
/**
* 从FTP上下载文件的路径
*/
private String downloadPath;
/**
* 上传文件到FTP的路径
*/
private String uploadPath;
/**
* 连接FTP服务器
*
* @return ftpClient ftp服务器连接对象
*/
private FTPClient connectFTPClient() {
FTPClient ftpClient = new FTPClient();
try {
ftpClient = new FTPClient();
ftpClient.connect(host, port);// 连接FTP服务器
ftpClient.login(userName, password);// 登陆FTP服务器
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
logger.info("连接TFP,host={},port={},userName={},passWord={}", host,port,userName,password);
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
logger.error("连接FTP失败,用户名或密码错误!");
ftpClient.disconnect();
} else {
logger.info("FTP连接成功!");
}
} catch (Exception e) {
logger.error("error:", e);
}
return ftpClient;
}
/**
* 从ftp服务器批量下载文件
*
* @param localPath
* 下载文件在本地的保存路径
* @param ftpFileNames
* 需要下载的文件列表
*
* @return true 下载成功 false下载失败
*/
public boolean downloadFilesFromFTP(String localPath, String[] ftpFileNames) {
FTPClient ftpClient = null;
OutputStream os = null;
InputStream in = null;
boolean isDownloadSuccess = false;
try {
ftpClient = connectFTPClient();
if (ftpClient == null) {
return false;
}
if (!ftpClient.changeWorkingDirectory(downloadPath)) {
logger.error("FTP目录切换失败");
return false;
}
for (String ftpFileName : ftpFileNames) {
logger.info("FTP下载路径{},文件{}", downloadPath, ftpFileName);
// 判断FTP上文件是否存在
in = ftpClient.retrieveFileStream(ftpFileName);
if (in == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE) {
logger.error("FTP服务器上文件 " + downloadPath + ftpFileName + "不存在!");
return false;
}
ftpClient.completePendingCommand();
if (in != null) {
in.close();
}
// 从ftp上下载文件
File localFile = new File(localPath + ftpFileName);
if (localFile.exists()) {
localFile.delete();
}else {
if (!localFile.getParentFile().exists()) {
localFile.getParentFile().mkdirs();
}
}
localFile.createNewFile();
os = new FileOutputStream(localFile);
if (!ftpClient.retrieveFile(localFile.getName(), os)) {
logger.error("文件" + downloadPath + ftpFileName + "下载失败!");
return false;
}
}
ftpClient.logout();
isDownloadSuccess = true;
} catch (Exception e) {
logger.error("error", e);
} finally {
if (os != null) {
try {
os.flush();
os.close();
} catch (IOException e) {
logger.error("FileOutputStream关闭失败:", e);
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
logger.error("FileInputStream关闭失败:", e);
}
}
if (ftpClient != null && ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
logger.error("FTP连接关闭失败:", e);
}
}
}
return isDownloadSuccess;
}
/**
* 批量上传文件到ftp服务器
*
* @param localFile
* 上传的文件数组
* @return true 上传成功 false 上传失败
*/
public boolean uploadFilesToFTP(File[] localFiles) {
FileInputStream in = null;
FTPClient ftpClient = null;
ByteArrayInputStream byteIn = null;
try {
ftpClient = connectFTPClient();
if (ftpClient == null) {
return false;
}
if (!ftpClient.changeWorkingDirectory(uploadPath)) {
logger.error("FTP目录切换失败");
return false;
}
// 上传文件
for (File localFile : localFiles) {
logger.info("FTP上传路径:{},文件={}", uploadPath,localFile.toString());
in = new FileInputStream(localFile);
ByteArrayOutputStream resout = new ByteArrayOutputStream();
int read = -1;
byte[] indata = new byte[BYTE_SIZE];
while ((read = in.read(indata)) != -1) {
resout.write(indata, 0, read);
}
byteIn = new ByteArrayInputStream(resout.toByteArray());
ftpClient.storeFile(localFile.getName(), byteIn);
if (in != null) {
in.close();
}
if (byteIn != null) {
byteIn.close();
}
}
ftpClient.logout();
return true;
} catch (Exception e) {
logger.error("error:", e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
logger.error("FileInputStream关闭失败:", e);
}
}
if (byteIn != null) {
try {
byteIn.close();
} catch (Exception e) {
logger.error("FileInputStream关闭失败:", e);
}
}
if (ftpClient != null && ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
logger.error("FTP连接关闭失败:", e);
}
}
}
return false;
}
public boolean isFileExists(String ftpFileName) {
boolean exist = false;
FTPClient ftpClient = null;
InputStream in = null;
try {
ftpClient = connectFTPClient();
if (ftpClient == null) {
return false;
}
if (!ftpClient.changeWorkingDirectory(downloadPath)) {
logger.error("FTP目录切换失败");
return false;
}
logger.info("FTP下载路径{},文件{}", downloadPath, ftpFileName);
// 判断FTP上文件是否存在
in = ftpClient.retrieveFileStream(ftpFileName);
if (in == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE) {
logger.error("FTP服务器上文件 " + downloadPath + ftpFileName + "不存在!");
return false;
}
ftpClient.completePendingCommand();
exist = true;
} catch(Exception e){
logger.error("判断FTP上文件是否存出错:", e);
}finally{
if (in != null) {
try {
in.close();
} catch (IOException e) {
logger.error("FileInputStream关闭失败:", e);
}
}
if (ftpClient != null && ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException e) {
logger.error("FTP连接关闭失败:", e);
}
}
}
return exist;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int 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 String getDownloadPath() {
return downloadPath;
}
public void setDownloadPath(String downloadPath) {
this.downloadPath = downloadPath;
}
public String getUploadPath() {
return uploadPath;
}
public void setUploadPath(String uploadPath) {
this.uploadPath = uploadPath;
}
}
工具类 FTPUtil .java
最新推荐文章于 2021-05-06 22:19:28 发布