package com.test.ftp.impl;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import sun.net.TelnetInputStream;
import sun.net.TelnetOutputStream;
import sun.net.ftp.FtpClient;
import ftp.FtpBean;
import ftp.FtpException;
import ftp.FtpListResult;
import ftp.FtpObserver;
**
* 文件FTP下载上传工具类
*
public class FtpUtil implements FtpObserver {
private final static Log logger = LogFactory.getLog(FtpUtil.class);
private FtpUtilParams ftpUtilParams;
FtpBean ftp;
long num_of_bytes_read = 0;
long num_of_bytes_write = 0;
public FtpUtil() {
ftp = new FtpBean();
}
**
* 获得Ftp服务器当前目录下有多少符合过滤条件的文件
*
* @param path
* @param host
* @param username
* @param password
* @param filters
* 文件扩展名数组 例如:{"exe","txt"}
* @return
*
public long getFilterFtpFileCount(String path, String host,
String username, String password, String[] filters)
throws FtpException {
try {
ftp.ftpConnect(host, username, password);
} catch (FtpException e) {
throw new FtpException("连接ftp服务器失败,请确认ftp连接参数是否设置正确");
} catch (IOException e) {
throw new FtpException("连接ftp服务器失败," + e.getLocalizedMessage());
}
try {
ftp.setDirectory(path);
FtpListResult ftplrs = ftp.getDirectoryContent();
long i = 0, j = 0;
while (ftplrs.next()) {
int type = ftplrs.getType();
if (type == FtpListResult.FILE) {
i++;
String file = ftplrs.getName();
int len = file.lastIndexOf(".");
// 文件有可能没有文件扩展名,即没有.,例如linux下的文件,滤掉不处理
if (len > 0) {
String tmpFile = file.substring(0, len);
// 对于用我们的FTP控件上传的文件,自动加了版本号,如.001,需要滤掉
if (tmpFile.lastIndexOf(".") > 0) {
file = tmpFile;
}
}
logger.debug("第" + i + "个文件是:" + file);
String[] splitFile = file.split("\\.");
String extName = splitFile[splitFile.length - 1];
logger.debug("第" + i + "个文件后缀是:" + extName);
if (isContainedFile(extName, filters)) {
j++;
}
}
}
logger.debug("文件数量:" + i);
logger.debug("符合过滤条件的文件数量:" + j);
return j;
} catch (FtpException ex) {
throw new FtpException("Ftp服务器上没有相应目录");
} catch (Exception e) {
e.printStackTrace();
throw new FtpException("目前系统还没有上传相关数据!");
}
}
**
* 判断文件的扩展名是否在要求的filter中
*
* @param extName
* @param filters
* 文件扩展名数组 例如:{"exe","txt"}
* @return
*
private boolean isContainedFile(String extName, String[] filters) {
boolean ret = false;
// 如果没有,则不过滤
if (filters == null || filters.length < 1) {
ret = true;
return ret;
}
for (int i = 0; i < filters.length; i++) {
if (extName.equalsIgnoreCase(filters[i])) {
ret = true;
break;
}
}
return ret;
}
**
* 删除Ftp服务器当前目录下的所有文件
*
* @param path
* @param host
* @param username
* @param password
* @throws FtpException
*
public void deleteFtpFiles(String path, String host, String username,String password) throws FtpException {
try {
ftp.ftpConnect(host, username, password);
} catch (FtpException e) {
throw new FtpException("连接ftp服务器失败,请确认ftp连接参数是否设置正确");
} catch (IOException e) {
throw new FtpException("连接ftp服务器失败," + e.getLocalizedMessage());
}
try {
ftp.setDirectory(path);
FtpListResult ftplrs = ftp.getDirectoryContent();
while (ftplrs.next()) {
int type = ftplrs.getType();
if (type == FtpListResult.FILE) {
String filename = ftplrs.getName();
ftp.fileDelete(filename);
}
}
} catch (FtpException e) {
throw e;
} catch (IOException e) {
throw new FtpException("IO异常");
}
}
* 下载文件
*
* @param localeFile
* 本地文件名
* @param remoteFile
* 远程文件名
* @param path
* Ftp登录后的相对路径
* @param host
* 主机名
* @param username
* 用户名
* @param password
* 密码
* @return 0 成功 1 失败
* @throws FileNotFoundException
* @throws IOException
public static void downloadFile(String localeFile, String remoteFile,
String path, String host, String username, String password)
throws FtpException {
FtpClient client = null;
RandomAccessFile getFile = null;
TelnetInputStream fget = null;
DataInputStream puts = null;
try {
client = getConnect(path, host, username, password);
int ch;
File file = new File(localeFile);
getFile = new RandomAccessFile(file, "rw");
getFile.seek(0);
fget = client.get(remoteFile);
puts = new DataInputStream(fget);
while ((ch = puts.read()) >= 0) {
getFile.write(ch);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
throw new FtpException("请确认文件是否存在!");
} catch (IOException ex) {
ex.printStackTrace();
throw new FtpException("文件读取异常");
} finally {
try {
if (fget != null)
fget.close();
if (getFile != null)
getFile.close();
if (client != null)
client.closeServer();
} catch (IOException e) {
throw new FtpException("流关闭异常");
}
}
}
**
* 把一个端服务器上的文件FTP到另一个服务器.
* 服务器可以都是远端服务器
*
public int ftpFileFromOneAddressToOtherAddress(FtpUtilParams transParam) throws FtpException {
FtpClient origClient = null;
FtpClient aimClient = null;
TelnetInputStream fget = null;
TelnetOutputStream out = null;
try {
if (logger.isDebugEnabled()) {
logger.debug("ftpParams ==" + transParam);
}
origClient = getConnect(transParam.getOrigPath(), transParam
.getOrigHost(), transParam.getOrigUserName(), transParam
.getOrigPassword());
if (origClient == null) {
return 1;
}
aimClient = getConnect(transParam.getAimPath(), transParam
.getAimHost(), transParam.getAimUserName(), transParam
.getAimPassword());
if (aimClient == null) {
return 1;
}
File file = new File(transParam.getAimFileName());
fget = origClient.get(transParam.getOrigFileName());
out = aimClient.put(file.getName());
int c = 0;
while ((c = fget.read()) != -1) {
out.write(c);
}
return 1;
} catch (FileNotFoundException ex) {
throw new FtpException("请确认文件是否存在!");
} catch (IOException exp) {
throw new FtpException("文件读取异常");
} finally {
try {
if (out != null)
out.close();
if (fget != null)
fget.close();
if (aimClient != null)
aimClient.closeServer();
if (origClient != null)
origClient.closeServer();
} catch (IOException e) {
throw new FtpException("流关闭异常");
}
}
}
**
* FTP文件到指定的服务器上。(注意:如果是在广域网上传输,此方法会有问题,不能上传。)
*
* @param fileName
* 上传文件名
* @param path
* Ftp登录后的相对路径
* @param host
* 主机名
* @param username
* 用户名
* @param password
* 密码
* @return 0 成功 1 失败
* @throws IOException
* @throws FileNotFoundException
*
public static int uploadFile(String fileName, String path, String host,
String username, String password) throws FtpException {
FtpClient client = getConnect(path, host, username, password);
FileInputStream in = null;
TelnetOutputStream out = null;
if (client == null) {
return 1;
}
try {
File file = new File(fileName);
in = new FileInputStream(file);
out = client.put(file.getName());
int c = 0;
while ((c = in.read()) != -1) {
out.write(c);
}
return 0;
} catch (FileNotFoundException ex) {
logger.debug("没有要上传的文件,请确认!");
return 1;
} catch (IOException exp) {
throw new FtpException("文件读取异常");
} finally {
try {
if (in != null)
in.close();
if (out != null)
out.close();
if (client != null)
client.closeServer();
} catch (IOException e) {
throw new FtpException("流关闭异常");
}
}
}
* @param path
* Ftp登录后的相对路径
* @param host
* 主机名
* @param username
* 用户名
* @param password
* 密码
* @return
* @throws IOException
private static FtpClient getConnect(String path, String host,
String username, String password) throws FtpException {
try {
FtpClient client = new FtpClient(host);
client.login(username, password);
client.binary();
client.cd(path);
return client;
} catch (IOException ex) {
throw new FtpException("连接ftp服务器失败,请确认ftp连接参数是否设置正确");
}
}
// Implemented for FtpObserver interface.
// To monitor download progress.
public void byteRead(int bytes) {
// num_of_bytes_read += bytes;
// System.out.println(num_of_bytes_read + " of bytes read already.");
}
// Needed to implements by FtpObserver interface.
public void byteWrite(int bytes) {
// num_of_bytes_write += bytes;
// System.out.println(num_of_bytes_write + " of bytes read already.");
}
public FtpUtilParams getFtpUtilParams() {
return ftpUtilParams;
}
public void setFtpUtilParams(FtpUtilParams ftpUtilParams) {
this.ftpUtilParams = ftpUtilParams;
}
}
package com.test.ftp.impl;
**
* 这只是一个参数封装类,用于传递参数到FtpUtil。
*
public class FtpUtilParams {
private String aimFileName;
private String origFileName;
private String aimPath;
private String origPath;
private String aimHost;
private String origHost;
private String aimUserName;
private String origUserName;
private String aimPassword;
private String origPassword;
public void setAimFileName(String aimFileName){
this.aimFileName = aimFileName;
}
public void setAimHost(String aimHost) {
this.aimHost = aimHost;
}
public void setAimPath(String aimPath) {
this.aimPath = aimPath;
}
public void setAimUserName(String aimUserName) {
this.aimUserName = aimUserName;
}
public void setOrigFileName(String origFileName) {
this.origFileName = origFileName;
}
public void setOrigHost(String origHost) {
this.origHost = origHost;
}
public void setAimPassword(String aimPassword) {
this.aimPassword = aimPassword;
}
public void setOrigPassword(String origPassword) {
this.origPassword = origPassword;
}
public void setOrigPath(String origPath) {
this.origPath = origPath;
}
public void setOrigUserName(String origUserName) {
this.origUserName = origUserName;
}
public String getAimFileName() {
return aimFileName;
}
public String getAimHost() {
return aimHost;
}
public String getAimPassword() {
return aimPassword;
}
public String getAimPath() {
return aimPath;
}
public String getAimUserName() {
return aimUserName;
}
public String getOrigFileName() {
return origFileName;
}
public String getOrigHost() {
return origHost;
}
public String getOrigPassword() {
return origPassword;
}
public String getOrigPath() {
return origPath;
}
public String getOrigUserName() {
return origUserName;
}
public String toString() {
return " aimFileName = "+ aimFileName
+" ,origFileName ="+ origFileName
+" ,aimPath ="+ aimPath
+" ,origPath ="+ origPath
+" ,aimHost ="+ aimHost
+" ,origHost ="+ origHost
+" ,aimUserName ="+ aimUserName+" ,origUserName ="+ origUserName
+" ,aimPassword ="+ aimPassword+" ,origPassword ="+ origPassword;
}
}
package com.test.ftp.impl;
@SuppressWarnings(“serial”)
public class FtpException extends RuntimeException {
public FtpException() {
super();
}
public FtpException(String message) {
super(message);
}
public FtpException(String message, Throwable cause) {
super(message, cause);
}
public FtpException(Throwable cause) {
super(cause);
}
}