package com.joyveb.lottery.util;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.StringTokenizer;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import com.joyveb.lottery.util.exception.FtpConnectException;
import com.joyveb.lottery.util.exception.FtpDownException;
import com.joyveb.lottery.util.exception.FtpUploadException;
public class FtpUtil {
/** FTP地址 **/
private String host;
/** FTP端口 **/
private int port;
/** FTP用户名 **/
private String username;
/** FTP密码 **/
private String password;
/** FTP连接超时时间 */
private int connectTimeout = 10000;
/** 数据读写超时时间 */
private int dataTimeout = 10000;
private String tmppostfix = ".tmp";
private FTPClient ftpClient = null;
public FtpUtil() {
ftpClient = new FTPClient();
}
public FtpUtil(String host, int port, String username, String password) {
this();
this.host = host;
this.port = port;
this.username = username;
this.password = password;
}
/**
* 连接ftp
*
* @throws FtpConnectException
*/
public void connect() throws FtpConnectException {
try {
ftpClient.setConnectTimeout(this.connectTimeout);
ftpClient.setDataTimeout(this.dataTimeout);
ftpClient.connect(this.host, this.port);
ftpClient.setControlEncoding("GBK");
ftpClient.enterLocalPassiveMode();
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
if (!ftpClient.login(this.username, this.password)) {
throw new FtpConnectException(new StringBuffer()
.append("FTP登录失败,帐号或者密码错误ip:").append(host)
.append(",port:").append(port).append(",username:")
.append(username).append(",password:")
.append(password).toString());
}
}
} catch (IOException e) {
throw new FtpConnectException(new StringBuffer()
.append("连接FTP服务器异常ip:").append(host).append(",port:")
.append(port).append(",username:").append(username)
.append(",password:").append(password).toString(), e);
}
}
// /**
// * Ftp上传,并校验
// *
// * @param localpath
// * @param remotepath
// * @throws FtpUploadException
// */
// public void uploadVail(String identify, String localpath, String
// remotepath)
// throws FtpUploadException {
// File tmpFile = null;
// try {
// File remotefile = new File(remotepath);
// this.delete(remotefile.getParent(), remotefile.getName());
// this.upload(localpath, remotepath + tmppostfix);
// this.download(Constants.TMPDIR + remotefile.getName() + identify,
// remotepath + tmppostfix);
// tmpFile = new File(Constants.TMPDIR + remotefile.getName()
// + identify);
// FileHelp.md5Check(tmpFile, new File(localpath));
// this.rename(remotefile.getParent(), remotefile.getName()
// + tmppostfix, remotefile.getName());
// } catch (Exception e) {
// throw new FtpUploadException(
// StringUtil.getStrBuffer().append("FTP文件校验上传异常ip:")
// .append(host).append(",port:").append(port)
// .append(",file:").append(localpath).toString(), e);
// } finally {
// if (tmpFile != null && tmpFile.exists()) {
// tmpFile.delete();
// }
// }
// }
/**
* FTP上传
*
* @param localpath
* @param remotepath
* @throws FtpUploadException
*/
public void upload(String localpath, String remotepath)
throws FtpUploadException {
FileInputStream fis = null;
try {
// 设置以二进制流的方式传输
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
File remoteFile = new File(remotepath);
ftpClient.changeWorkingDirectory("/");
if (remoteFile.getParent() != null
&& !ftpClient
.changeWorkingDirectory(remoteFile.getParent())) {
this.createDir(remoteFile.getParent());
}
fis = new FileInputStream(localpath);
if (remoteFile.exists()) {
remoteFile.delete();
}
ftpClient.storeFile(
new String((remoteFile.getName() + tmppostfix).getBytes(),
ftpClient.getControlEncoding()), fis);
ftpClient.rename(
new String((remoteFile.getName() + tmppostfix).getBytes(),
ftpClient.getControlEncoding()),
new String(remoteFile.getName().getBytes(), ftpClient
.getControlEncoding()));
} catch (Exception e) {
throw new FtpUploadException(
new StringBuffer().append("FTP文件上传异常ip:").append(host)
.append(",port:").append(port).append(",file:")
.append(localpath).toString(), e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
throw new FtpUploadException(e);
}
}
}
}
/**
* 修改名字
*
* @param remotepath
* @param newName
* @throws UnsupportedEncodingException
* @throws IOException
*/
public void rename(String dir, String oldName, String newName)
throws UnsupportedEncodingException, IOException {
if (StringUtils.isNotBlank(dir)) {
this.changerToPath(dir);
}
ftpClient.rename(
new String(oldName.getBytes(), ftpClient.getControlEncoding()),
new String(newName.getBytes(), ftpClient.getControlEncoding()));
}
/**
* 删除文件
*
* @param dir
* @param fileName
* @throws IOException
*/
public void delete(String dir, String fileName) throws IOException {
if (StringUtils.isNotBlank(dir)) {
this.changerToPath(dir);
}
ftpClient.deleteFile(new String(fileName.getBytes(), ftpClient
.getControlEncoding()));
}
/**
* 下载FTP文件
*
* @param localpath
* @param remotepath
* @throws FtpDownException
*/
public void download(String localpath, String remotepath)
throws FtpDownException {
BufferedOutputStream bos = null;
try {
ftpClient.changeWorkingDirectory("/");
// 设置以二进制流的方式传输
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
File remoteFile = new File(remotepath);
File localFile = new File(localpath);
if (localFile.getParent() != null) {
File localpfile = localFile.getParentFile();
if (!localpfile.exists()) {
if (!localpfile.mkdirs()) {
throw new FtpDownException("创建目录失败:"
+ localpfile.getPath());
}
}
}
if (remoteFile.getParent() != null) {
this.changerToPath(remoteFile.getParent());
}
bos = new BufferedOutputStream(new FileOutputStream(localFile));
ftpClient.retrieveFile(new String(remoteFile.getName().getBytes(),
ftpClient.getControlEncoding()), bos);
bos.flush();
} catch (Exception e) {
throw new FtpDownException(
new StringBuffer().append("FTP文件下载异常ip:").append(host)
.append(",port:").append(port).append(",file:")
.append(localpath).toString(), e);
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
throw new FtpDownException(e);
}
}
}
}
/**
* 转到目录下
*
* @param dir
* @throws IOException
* @throws Exception
*/
private void changerToPath(String dir) throws IOException {
StringBuffer sb = new StringBuffer();
File file = new File(dir);
File pfile = file.getParentFile();
sb.append(file.getName());
while (pfile != null) {
sb.insert(0, pfile.getName() + "/");
pfile = pfile.getParentFile();
}
ftpClient.changeWorkingDirectory("/");
StringTokenizer s = new StringTokenizer(sb.toString(), "/");
s.countTokens();
String pathName = "";
while (s.hasMoreElements()) {
pathName = (String) s.nextElement();
ftpClient.changeWorkingDirectory(pathName);
}
}
/**
* 创建文件夹
*
* @param dir
* @throws IOException
* @throws Exception
*/
private void createDir(String dir) throws IOException {
ftpClient.changeWorkingDirectory("/");
StringBuffer sb = new StringBuffer();
File file = new File(dir);
File pfile = file.getParentFile();
sb.append(file.getName());
while (pfile != null) {
sb.insert(0, pfile.getName() + "/");
pfile = pfile.getParentFile();
}
StringTokenizer s = new StringTokenizer(sb.toString(), "/");
s.countTokens();
while (s.hasMoreElements()) {
String pathName = (String) s.nextElement();
if (!ftpClient.changeWorkingDirectory(pathName)) {
ftpClient.makeDirectory(pathName);
ftpClient.changeWorkingDirectory(pathName);
}
}
}
/**
* 断开与远程服务器的连接
*
* @throws IOException
*
*/
public void disconnect() throws IOException {
if (ftpClient != null && ftpClient.isConnected()) {
ftpClient.disconnect();
}
}
/**
* 获取FTP地址
*
* @return
*/
public String getHost() {
return host;
}
/**
* 设置FTP地址
*
* @param host
*/
public void setHost(String host) {
this.host = host;
}
/**
* 获取FTP端口
*
* @return
*/
public int getPort() {
return port;
}
/**
* 设置FTP端口
*
* @param port
*/
public void setPort(int port) {
this.port = port;
}
/**
* 获取FTP用户名
*
* @return
*/
public String getUsername() {
return username;
}
/**
* 设置FTP用户名
*
* @param username
*/
public void setUsername(String username) {
this.username = username;
}
/**
* 获取FTP密码
*
* @return
*/
public String getPassword() {
return password;
}
/**
* 设置FTP密码
*
* @param password
*/
public void setPassword(String password) {
this.password = password;
}
}