0
点赞
收藏
分享

微信扫一扫

FTP 上传下载工具类


1.工具类

public class FTPOperator {
/*
* FTP操作
* */

private static final Logger log = Logger.getLogger(FTPOperator.class);

private static FTPOperator ftpOperator;

/*
* 构造方法
* */
private FTPOperator(){}

/*
* 获取实例
* */
public static synchronized FTPOperator getInstance(){
if(ftpOperator == null){
ftpOperator = new FTPOperator();
}

return ftpOperator;
}

/*
* 获取FTP连接
* */
private FTPClient connectionServer(String ip, int port, String protocol){
FTPClient ftp = null;
if(protocol == null){
ftp = new FTPClient();
}else{
FTPSClient ftps;
if (protocol.equals("true")) {
ftps = new FTPSClient(true);
} else if (protocol.equals("false")) {
ftps = new FTPSClient(false);
} else {
String prot[] = protocol.split(",");
if (prot.length == 1) { // Just protocol
ftps = new FTPSClient(protocol);
} else { // protocol,true|false
ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
}
}
ftp = ftps;
}

//设置等待时间为1个小时
ftp.setControlKeepAliveReplyTimeout(3600000);
ftp.setControlKeepAliveTimeout(3600000);


try {
//连接服务器
ftp.connect(ip, port);

log.info("Connected to " + ip + " on " + port + "...");

// After connection attempt, you should check the reply code to verify
// success.
int reply = ftp.getReplyCode();

if (!FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();
log.error("FTP server refused connection.");
return null;
}
} catch (SocketException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}

log.info("Connected to " + ip + " on " + port + " successful.");

return ftp;
}

/*
* 关闭FTP连接
* */
private void closeConnection(FTPClient ftp){
if(ftp.isConnected()) {
try{
ftp.disconnect();
} catch (IOException f) {
log.warn("Close connect to server failed.");
}
}
log.warn("Close connect to server successful.");
}

/*
* 创建FTP服务器路径
* */
public boolean createRemoteDir(FTPClient client, String remoteDir){
try{
String dirName = new String(remoteDir.getBytes("gbk"), "iso-8859-1");
String convertedDirName = dirName.replace('\\', '/');
if(!convertedDirName.startsWith("/")){
log.error("请检查所配置的目录,应该配置为绝对路径 !");
return false;
}
if(convertedDirName.endsWith("/")){
convertedDirName = convertedDirName.substring(1, convertedDirName.length() - 1);
}else{
convertedDirName = convertedDirName.substring(1);
}

String [] dirArr = convertedDirName.split("/");
StringBuffer dirBuf = new StringBuffer("/");
for(int i=0; i<dirArr.length; ++i){
dirBuf.append(dirArr[i]).append("/");
checkPathExist(client, dirBuf.toString());
}


}catch(Exception e){
log.error("create remote dir " + remoteDir + "is failed!", e);
return false;
}

return true;
}

/*
* 检查目录是否存在
* */
private boolean checkPathExist(FTPClient client,String filePath) {
try {
if (!client.changeWorkingDirectory(filePath)) {
client.makeDirectory(filePath);
}
} catch (IOException e) {
e.printStackTrace();
}
return true;
}

/*
* 更换工作路径
* */
public boolean changeDir(FTPClient ftpClient, String remoteDir){
try {
String dirName = new String(remoteDir.getBytes("gbk"), "iso-8859-1");
if (!ftpClient.changeWorkingDirectory(dirName)) {
log.error("change to directory \"" + dirName + "\" failed!");
log.error("remote path is not exist.");
}
} catch (IOException e) {
log.error("Change remote to directory \"" + remoteDir
+ "\" is failed!", e);
return false;
}

log.info("切换工作路径成功:" + remoteDir);

return true;
}

/*
* 上传
* params:
* ip:IP地址
* port:端口
* protocol:SSL protocol,默认为空
* */
public void upload(String ip, int port, String protocol, boolean isPassiveMode, String userId, String password, String dir, String fileName, String remoteFileName){
FTPClient ftpClient = this.connectionServer(ip, port, protocol);
if(userId != null && !"".equals(userId)){
boolean ret = false;
try {
ret = ftpClient.login(userId, password);
} catch (IOException e) {
log.error("Login ftp server " + ip + " by userId " + userId + " and password " + password + "failed.");
e.printStackTrace();
return;
}
if(!ret){ //登录失败,退出
return;
}
}
// 采用被动模式失败,换为主动模式
if (isPassiveMode) {
ftpClient.enterLocalPassiveMode();
} else {
ftpClient.enterLocalActiveMode();
}

//检查远程路径是否存在,如果不存在则创建
checkPathExist(ftpClient, dir);

changeDir(ftpClient, dir);

FileInputStream is = null;
try {
java.io.File file_in = new java.io.File(fileName);
if (!file_in.exists()){
log.warn("要上传的文件不存在!");
return;
}

if (file_in.length() == 0){
log.error("需要上传的文件为空");
return;
}

is = new FileInputStream(file_in);

// ftpClient.deleteFile(tempFileName);
// ftpClient.deleteFile(remoteFileName);

if (is != null) {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
log.info("开始上传文件: " + remoteFileName);
if (ftpClient.storeFile(new String(remoteFileName.getBytes("gbk"), "iso-8859-1"), is)) {
log.info("上传文件成功");
// if(!ftpClient.rename(tempFileName, new String(remoteFileName.getBytes("gbk"), "iso-8859-1"))){
// log.error("文件: " + tempFileName + " 改名为: " + remoteFileName + " 失败!");
// }
} else {
log.error("上传文件失败!");
}
}
} catch(Exception e){
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

if(userId != null && !"".equals(userId)){
try {
ftpClient.logout();
} catch (IOException e) {
log.error("Logout ftp server failed.");
e.printStackTrace();
}
}

this.closeConnection(ftpClient);
}

/*
* 下载
* return: 工单系统文件唯一名称
* */
public String download(String ip, int port, String protocol, boolean isPassiveMode, boolean isWaitComplete,
String userId, String password, String remoteDir, String localDir, String remoteFileName){
FTPClient ftpClient = this.connectionServer(ip, port, protocol);
if(userId != null && !"".equals(userId)){
boolean ret = false;
try {
ret = ftpClient.login(userId, password);
} catch (IOException e) {
log.error("Login ftp server " + ip + " by userId " + userId + " and password " + password + "failed.");
e.printStackTrace();
return null;
}
if(!ret){ //登录失败,退出
log.error("Login ftp server " + ip + " by userId " + userId + " and password " + password + "failed.");
return null;
}
}
// 采用被动模式失败,换为主动模式
if (isPassiveMode) {
ftpClient.enterLocalPassiveMode();
} else {
ftpClient.enterLocalActiveMode();
}

//检查远程路径是否存在,如果不存在则创建
// checkPathExist(ftpClient, remoteDir);

try {
ftpClient.changeWorkingDirectory(remoteDir);
} catch (IOException e1) {
e1.printStackTrace();
}

UUID localFileName = UUID.randomUUID();

String timpFile = localFileName.toString() + ".tmp";

InputStream is = null;
FileOutputStream os = null;


try {
String ftpFileName = new String(remoteFileName.getBytes("gbk"), "iso-8859-1");
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
// 是否等待采用二进制方式传递文件时返回的 Reply
if (isWaitComplete) {
ftpClient.completePendingCommand();
}
is = ftpClient.retrieveFileStream(ftpFileName);
if (is == null) {
log.error("Download file:" + ftpFileName + " failed!");
return null;
}
File tempOutfile = new File(timpFile);
os = new FileOutputStream(timpFile);
byte[] bytes = new byte[1024];
int c;
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
os.close();
File outFile = new File(localDir + "/" + localFileName.toString());
if (outFile.exists()) {
outFile.delete();
}
tempOutfile.renameTo(outFile);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
if (!ftpClient.completePendingCommand()) {
log.error("Close InputStream of remote file" + remoteFileName
+ "failed!");
Exception e = new Exception("Close InputStream of remote file"
+ remoteFileName + "failed!");
throw e;
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}

}

if(userId != null && !"".equals(userId)){
try {
ftpClient.logout();
} catch (IOException e) {
log.error("Logout ftp server failed.");
e.printStackTrace();
}
}

this.closeConnection(ftpClient);

log.info("下载文件:" + remoteFileName + "完成");

return localFileName.toString();
}


2.调用工具类代码

PropertiesParser prop = new PropertiesParser();
String attachFilePath = prop.getProperty("attachPath");
String ip = prop.getProperty("FtpServerIp");
String port = prop.getProperty("FtpServerPort");
String userId = prop.getProperty("FtpLoginUserId");
String password = prop.getProperty("FtpLoginPassword");
String remoteDir = prop.getProperty("FtpRemoteDir");
boolean isPassiveMode = false;
if("true".equals(prop.getProperty("FtpIsPassiveMode"))){
isPassiveMode = true;
}

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

// /WorkPlan/WorkPlan_G/Data/201203/01/11701/Form/a_120402.xml
String date = sdf.format(new Date());
remoteDir = remoteDir + "/" + date.substring(0,6) + "/" + date.substring(6,8)
+ "/" + order.getCityId() + "/Form";

FTPOperator ftpOperator = FTPOperator.getInstance();
StringBuilder remoteFile = new StringBuilder();
String[] attachArray = vtriuslFileList.split(";");
String[] attachNameArray = filePath.split(";");


String fileName = attachFilePath + "/" + attachArray[0]; //唯一名称
String attachName = attachNameArray[0]; //真实名称
String remoteName = attachName.substring(0, attachName.lastIndexOf("."))
+ "_" + sdf.format(new Date()) + attachName.substring(attachName.lastIndexOf("."));

log.info("开始上传文件:" + remoteName);
ftpOperator.upload(ip, Integer.parseInt(port), null, isPassiveMode, userId, password,
remoteDir, fileName, remoteName);
log.info("上传文件:" + remoteName + "完成");


3.XML配置文件

FtpServerIp=14.15.224.73
FtpServerPort=21
FtpIsPassiveMode=true
FtpIsWaitComplete=false
FtpLoginUserId=workplan
FtpLoginPassword=workplan
FtpRemoteDir=/Work/Data




举报

相关推荐

0 条评论