FTP服务器操作(连接,上传,下载,删除)

package com.ccbtrust.tm.sales.job.utils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.ccbtrust.utils.Constants;

/**
* FTP服务器操作(连接,上传,下载,删除)
*
* @author SunZhen 2015年11月11日 20:10:47
*
*/
public class FTPUtils {
/**
* 日志操作对象
*/
private static final Logger LOGGER = LoggerFactory
.getLogger(FTPUtils.class);
private static FTPUtils ftpUtils;

private static String propertyFile = "/加载服务器配置.properties"; // 配置文件
private static String host; // 服务器地址
private static int port; // 服务器端口
private static String userName; // 服务器用户名
private static String passWord; // 服务器密码
private static String path; // 服务器默认路径
private final int defaultTimeout = 300000; // 默认超时时间
private final int dataTimeout = 300000; // 数据传输超时时间
// private final int connectTimeout = 300000; // 连接超时时间
private InputStream is; // 文件下载输入流
private ThreadLocal<FTPClient> localClient = new ThreadLocal<FTPClient>();

private FTPUtils() {
initConfig();
}

/**
* 获取FTPUtils对象实例
*
* @return FTPUtils对象实例
*/
public static synchronized FTPUtils getInstance() {
if (null == ftpUtils) {
ftpUtils = new FTPUtils();
}
ftpUtils.localClient.set(new FTPClient( ));
return ftpUtils;
}

/**
* 初始化FTP服务器连接属性
*/
@SuppressWarnings("resource")
private void initConfig() {
Properties properties = new Properties(); // 构造Properties对象
InputStream in = null; // 定义配置文件输入流
try {
String filePath = this.getClass().getResource(propertyFile)
.getPath();
in = new FileInputStream(filePath);
in = FTPUtils.class.getResourceAsStream(propertyFile); // 获取配置文件输入流
properties.load(in); // 加载配置文件
host = properties.getProperty("host1");
port = Integer.parseInt(properties.getProperty("port1"));
userName = properties.getProperty("userName1");
passWord = properties.getProperty("passWord1");
path = properties.getProperty("path1");
in.close();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}

/**
* 与FTP服务器建立连接
*
* @param remotePath
* 访问路径
* @return true:成功;false:失败
*/
private boolean connect(String remotePath) {
boolean result = false;
try {
ftpUtils.localClient.get().connect(host, port); // 连接
ftpUtils.localClient.get().login(userName, passWord); // 登录
int reply = ftpUtils.localClient.get().getReplyCode();
// 判断返回码是否合法
if (!FTPReply.isPositiveCompletion(reply)) {
ftpUtils.localClient.get().disconnect(); // 断开连接
return result;
}
// 如果入参FTP文件路径缺省,使用配置文件中的默认路径
if ("".equals(remotePath) || null == remotePath
|| "undefined".equals(remotePath)) {
remotePath = path;
}
// ftpUtils.localClient.get().setControlEncoding("UTF-8"); // 设置字符集
// ftpUtils.localClient.get().setBufferSize(3072); // 设置缓冲区大小3M
ftpUtils.localClient.get().setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
ftpUtils.localClient.get().setFileType(FTP.BINARY_FILE_TYPE); // 设置传输方式为二进制

ftpUtils.localClient.get().setDefaultTimeout(defaultTimeout); // 设置默认超时时间
ftpUtils.localClient.get().setDataTimeout(dataTimeout); // 设置数据传输超时时间
// ftpUtils.localClient.get().setConnectTimeout(connectTimeout); // 设置连接超时时间

result = ftpUtils.localClient.get().changeWorkingDirectory(remotePath); // 设置指定路径
LOGGER.debug("设置ftp指定路径:"+remotePath+",结果为:"+result);
if (!result) {
checkPath(remotePath);
result = ftpUtils.localClient.get().changeWorkingDirectory(remotePath); // 设置指定路径
LOGGER.debug("设置ftp指定路径:"+remotePath+",结果为:"+result);
}
LOGGER.debug("连接建立成功");
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
LOGGER.error("连接建立失败");
}
return result;
}

/**
* 上传文件
*
* @param storePath
* 文件存储路径
* @param fileName
* 文件存储名称
* @param ins
* 文件输入流
* @return true:成功;false:失败
*/
public boolean storeFile(String storePath, String fileName, InputStream ins) {
boolean result = false;
try {
result = connect(storePath); // 建立连接
if (result) {
result = false;
LOGGER.debug("*****连接FTP服务器(" + host + ")成功,当前路径["
+ ftpUtils.localClient.get().printWorkingDirectory() + "],准备上传附件<"
+ fileName + ">*****");
result = ftpUtils.localClient.get().storeFile(new String(fileName.getBytes(),
"ISO-8859-1"), ins);
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
return false;
} finally {
if (null != ins) {
try {
ins.close();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
ftpUtils.logout(); // 登出服务器并断开连接
ftpUtils.localClient.remove();
}
return result;
}

/**
* 批量上传文件
*
* @param storePath
* [] 文件存储路径
* @param fileName
* List 文件存储名称
* @param MultipartFile
* [] 文件
* @return true:成功;false:失败
*/
public boolean storeFiles(String storePath, List<String> fileName,MultipartFile[] multipartFile) {
boolean result = false;
InputStream ins = null;
try {
result = connect(storePath); // 建立连接
if (result) {
result = false;
LOGGER.debug("*****连接FTP服务器(" + host + ")成功,当前路径["
+ ftpUtils.localClient.get().printWorkingDirectory() + "]>*****");
for(int i=0;i<fileName.size();i++){

LOGGER.debug("准备上传附件<" + fileName + ">");
ins = multipartFile[i].getInputStream();
result = ftpUtils.localClient.get().storeFile(new String(fileName.get(i).getBytes(),
"ISO-8859-1"), ins);
if(result){
LOGGER.debug("上传附件<" + fileName + ">成功");
}else{
LOGGER.debug("上传附件<" + fileName + ">失败");
}
}
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
LOGGER.debug("上传附件<" + fileName + ">失败");
return false;
} finally {
if (null != ins) {
try {
ins.close();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
ftpUtils.logout(); // 登出服务器并断开连接
ftpUtils.localClient.remove();
}
return result;
}

/**
* 下载文件
*
* @param remotePath
* 文件存储路径
* @param fileName
* 文件存储名称
* @param response
* @return true:成功;false:失败
*/
public boolean retrieveFile(String remotePath, String fileName,
HttpServletResponse response) {
boolean result = false;
OutputStream out = null;
try {
result = connect(remotePath); // 连接至服务器
if (result) {
result = false;
// ftpUtils.localClient.get().enterLocalPassiveMode(); // 设置被动模式
// FTPFile[] files = ftpUtils.localClient.get().listFiles();
String[] files = ftpUtils.localClient.get().listNames();
LOGGER.debug("*****连接FTP服务器(" + host + ")成功,当前路径["
+ ftpUtils.localClient.get().printWorkingDirectory() + "],共["
+ files.length + "]个文件,准备下载附件<" + fileName + ">*****");
String name = new String(fileName.getBytes(), "ISO-8859-1");
for (int i = 0; i < files.length; i++) {
String file = files[i];
if (name.equals(file)) {
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
fileName = new String(fileName.getBytes("GBK"),
"ISO-8859-1");
response.setHeader("Content-Disposition",
"attachment;filename=" + fileName);
out = response.getOutputStream();
result = ftpUtils.localClient.get().retrieveFile(file, out);
out.flush();
out.close();
break;
}
}
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
return false;
} finally {
if (null != out) {
try {
out.close();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
ftpUtils.logout(); // 登出服务器并断开连接
ftpUtils.localClient.remove();
}
return result;
}

/**
* 获取银行模板
*
* @param fileName
* @return
*/
public InputStream getFileIO(String filePath) {
boolean result = connect(Constants.BANKTEMP_PATH);
if (result) {
try {
String fileName = null;
LOGGER.info("文件路径/文件名:" + filePath);
LOGGER.debug("文件路径分割符号:" + Constants.FILE_SEPARATOR);
int lastIndexOf = filePath
.lastIndexOf(Constants.FILE_SEPARATOR);

if (lastIndexOf == -1) {
fileName = filePath;
} else {
fileName = filePath.substring(lastIndexOf,
filePath.length() - 1);
}
String[] files = ftpUtils.localClient.get().listNames();
LOGGER.debug("*****连接FTP服务器(" + host + ")成功,当前路径["
+ ftpUtils.localClient.get().printWorkingDirectory() + "],共["
+ files.length + "]个文件,目标文件<" + fileName + ">*****");
String name = new String(fileName.getBytes(), "ISO-8859-1");

for (int i = 0; i < files.length; i++) {
String file = files[i];
if (name.equals(file)) {
is = ftpUtils.localClient.get().retrieveFileStream(file);
result = true;
}
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
return is;
}

/**
* 获取文件
* @param filePath 文件路径
* @param fileName 文件名称
* @return
*/
public InputStream getFileIO(String filePath,String fileName) {
boolean result = connect(filePath);
if (result) {
try {
LOGGER.debug("文件路径/文件名:" + filePath);
LOGGER.debug("文件路径分割符号:" + Constants.FILE_SEPARATOR);

String[] files = ftpUtils.localClient.get().listNames();
LOGGER.debug("*****连接FTP服务器(" + host + ")成功,当前路径["
+ ftpUtils.localClient.get().printWorkingDirectory() + "],共["
+ files.length + "]个文件,目标文件<" + fileName + ">*****");
String name = new String(fileName.getBytes(), "ISO-8859-1");

for (int i = 0; i < files.length; i++) {
String file = files[i];
if (name.equals(file)) {
is = ftpUtils.localClient.get().retrieveFileStream(file);
result = true;
}else{
LOGGER.info("服务器暂无该文件,文件名称为:" + fileName);
}
}
} catch (Exception e) {
LOGGER.error(e.getMessage(), e);
}
}
return is;
}

/**
* 删除文件
*
* @param remotePath
* 文件存储路径
* @param fileName
* 文件存储名称
* @return true:成功;false:失败
*/
public boolean deleteFile(String remotePath, String fileName) {
boolean result = false;
try {
result = connect(remotePath); // 连接至服务器
if (result) {
result = false;
LOGGER.debug("*****连接FTP服务器(" + host + ")成功,当前路径["
+ ftpUtils.localClient.get().printWorkingDirectory() + "],准备删除附件<"
+ fileName + ">*****");
String[] files = ftpUtils.localClient.get().listNames();
String name = new String(fileName.getBytes(), "ISO-8859-1");
for (int i = 0; i < files.length; i++) {
String file = files[i];
if (name.equals(file)) {
result = ftpUtils.localClient.get().deleteFile(file);
break;
}
}
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
return false;
} finally {
ftpUtils.logout();
ftpUtils.localClient.remove();
}
return result;
}

/**
* 检测FTP服务器访问路径是否存在
*
* @param remotePath
* 文件存储路径
* @return
*/
private boolean checkPath(String remotePath) {
boolean result = false;
try {
FTPFile[] paths = ftpUtils.localClient.get().listDirectories();
for (int i = 0; i < paths.length; i++) {
FTPFile path = paths[i];
if (remotePath.equals(path.toString())) {
result = true;
}
}
if (!result) {

result = makeDir(remotePath);
LOGGER.debug("指定路径不存在创建路径:"+remotePath+",创建结果为:"+result);
}
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
return result;
}

/**
* 创建目录
*
* @param pathTmp
* 文件路径
* @return
*/
private boolean makeDir(String pathTmp) {
boolean result = false;
try {
result = ftpUtils.localClient.get().makeDirectory(pathTmp);
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
return result;
}

/**
* 登出服务器并断开连接 ftp FTPClient对象实例
*
* @return
*/
public boolean logout() {
boolean result = false;
if (null != is) {
try {
is.close();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
if (null != ftpUtils.localClient.get()) {
try {
result = ftpUtils.localClient.get().logout();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
} finally {
if (ftpUtils.localClient.get().isConnected()) {
try {
ftpUtils.localClient.get().disconnect();
} catch (IOException e) {
LOGGER.error(e.getMessage(), e);
}
}
}
}
return result;
}

}

posted @ 2019-11-22 10:05  阿昌先生  阅读(708)  评论(0)    收藏  举报