import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
//import org.apache.commons.net.ftp.FTPFile;
public class FtpUtil {
private final Logger logger = Logger.getLogger(FtpUtil.class);
FTPClient ftpClient = null;
private String ftpHost = null;
private String ftpPort = null;
private String ftpUserName = null;
private String ftpPassword = null;
/**
* 获取FTPClient对象
* @param ftpHost FTP主机服务器
* @param ftpPassword FTP 登录密码
* @param ftpUserName FTP登录用户名
* @param ftpPort FTP端口 默认为21
* @return
*/
public FTPClient getFTPClient() {
try {
ftpClient = new FTPClient();
ftpClient.connect(ftpHost, Integer.valueOf(ftpPort));// 连接FTP服务器
ftpClient.login(ftpUserName, ftpPassword);// 登陆FTP服务器
if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
logger.info("未连接到FTP,用户名或密码错误。");
ftpClient.disconnect();
} else {
logger.info("FTP连接成功。");
}
} catch (SocketException e) {
e.printStackTrace();
logger.info("FTP的IP地址可能错误,请正确配置。");
} catch (IOException e) {
e.printStackTrace();
logger.info("FTP的端口错误,请正确配置。");
}
return ftpClient;
}
/**
* 去 服务器的FTP路径下上读取文件
*
* @param ftpUserName
* @param ftpPassword
* @param ftpPath
* @param FTPServer
* @return
*/
public String readConfigFileForFTP(String ftpPath, String fileName) {
StringBuffer resultBuffer = new StringBuffer();
// FileInputStream inFile = null;
InputStream in = null;
FTPClient ftpClient = null;
logger.info("开始读取绝对路径" + ftpPath + "文件!");
try {
ftpClient = getFTPClient();
ftpClient.setControlEncoding("UTF-8"); // 中文支持
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.changeWorkingDirectory(ftpPath);
in = ftpClient.retrieveFileStream(fileName);
} catch (FileNotFoundException e) {
logger.error("没有找到" + ftpPath + "文件");
e.printStackTrace();
return "下载配置文件失败,请联系管理员.";
} catch (SocketException e) {
logger.error("连接FTP失败.");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
logger.error("文件读取错误。");
e.printStackTrace();
return "配置文件读取失败,请联系管理员.";
}
if (in != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String data = null;
try {
while ((data = br.readLine()) != null) {
resultBuffer.append(data );
}
} catch (IOException e) {
logger.error("文件读取错误。");
e.printStackTrace();
return "配置文件读取失败,请联系管理员.";
}finally{
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
logger.error("in为空,不能读取。");
return "配置文件读取失败,请联系管理员.";
}
return resultBuffer.toString();
}
/**
*
* 获取当前目录下下的文件列表
* @throws IOException
*
*/
public List<String> listAllFiles(String remotePath) throws IOException{
List<String> list = new ArrayList<String>();
ftpClient = getFTPClient();
FTPFile[] files = ftpClient.listFiles(remotePath);
for (int i = 0; i < files.length; i++) {
if (files[i].isFile()) {
System.out.println(files[i].getName());
list.add(files[i].getName());
} else if (files[i].isDirectory()) {
String currDirPath = remotePath + files[i].getName() + "/";
ftpClient.changeWorkingDirectory(currDirPath);
listAllFiles(currDirPath);
//System.out.println("监控工作目录切换:" + fileClient.printWorkingDirectory());
}
}
return list;
}
/**
<span style="white-space:pre"> </span> * 删除报文
<span style="white-space:pre"> </span> * @param remoteFileName 全路径下
<span style="white-space:pre"> </span> * @throws IOException
<span style="white-space:pre"> </span> */
<span style="white-space:pre"> </span>public boolean DeleteFile(String remoteFileName) throws IOException {
<span style="white-space:pre"> </span>boolean flag = false;
<span style="white-space:pre"> </span>String remoteFile = new String(remoteFileName.getBytes("UTF-8"),"UTF-8");
<span style="white-space:pre"> </span>try {
<span style="white-space:pre"> </span>flag = ftpClient.deleteFile(remoteFile);
<span style="white-space:pre"> </span>logger.info("文件"+remoteFile+"删除成功!");
<span style="white-space:pre"> </span>return flag;
<span style="white-space:pre"> </span>} catch (IOException ex) {
<span style="white-space:pre"> </span>logger.error(ex.getMessage());
<span style="white-space:pre"> </span>logger.error("Delete file failed");
<span style="white-space:pre"> </span>return flag;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
/**
* 本地上传文件到FTP服务器
*
* @param ftpPath
* 远程文件路径FTP
* @throws IOException
*/
public void upload(String ftpPath,String fileContent,
String writeTempFielPath) {
FTPClient ftpClient = null;
logger.info("开始上传文件到FTP.");
try {
ftpClient = getFTPClient();
// 设置PassiveMode传输
ftpClient.enterLocalPassiveMode();
// 设置以二进制流的方式传输
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
// 对远程目录的处理
String remoteFileName = ftpPath;
if (ftpPath.contains("/")) {
remoteFileName = ftpPath
.substring(ftpPath.lastIndexOf("/") + 1);
}
// FTPFile[] files = ftpClient.listFiles(new
// String(remoteFileName));
// 先把文件写在本地。在上传到FTP上最后在删除
boolean writeResult = write(remoteFileName, fileContent,
writeTempFielPath);
if (writeResult) {
File f = new File(writeTempFielPath + "/" + remoteFileName);
InputStream in = new FileInputStream(f);
ftpClient.storeFile(remoteFileName, in);
in.close();
logger.info("上传文件" + remoteFileName + "到FTP成功!");
f.delete();
} else {
logger.info("写文件失败!");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 把配置文件先写到本地的一个文件中取
*
* @param ftpPath
* @param str
* @return
*/
public boolean write(String fileName, String fileContext,
String writeTempFielPath) {
try {
logger.info("开始写配置文件");
File f = new File(writeTempFielPath + "/" + fileName);
if(!f.exists()){
if(!f.createNewFile()){
logger.info("文件不存在,创建失败!");
}
}
BufferedWriter bw = new BufferedWriter(new FileWriter(f, true));
bw.write(fileContext.replaceAll("\n", "\r\n"));
bw.flush();
bw.close();
return true;
} catch (Exception e) {
logger.error("写文件没有成功");
e.printStackTrace();
return false;
}
}
/**
* 重命名文件
*
* @param workDir --原路径
* @param workDir2 --新路径
* @param fileName --文件名
*/
public boolean renameFile(String workDir,String workDir2,String fileName) throws IOException {
FTPClient ftpClient = null;
boolean renameflag = false;
try{
logger.info("将文件"+fileName+"从"+workDir+"切换到目录"+workDir2+"下");
ftpClient = getFTPClient();
//切换至工作目录
ftpClient.changeWorkingDirectory(workDir);
renameflag = ftpClient.rename(fileName , workDir2 + fileName);
} catch (Exception e) {
e.printStackTrace();
logger.info("切换文件目录失败");
return false;
}finally{
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return renameflag;
}
public String getFtpHost() {
return ftpHost;
}
public void setFtpHost(String ftpHost) {
this.ftpHost = ftpHost;
}
public String getFtpPort() {
return ftpPort;
}
public void setFtpPort(String ftpPort) {
this.ftpPort = ftpPort;
}
public String getFtpUserName() {
return ftpUserName;
}
public void setFtpUserName(String ftpUserName) {
this.ftpUserName = ftpUserName;
}
public String getFtpPassword() {
return ftpPassword;
}
public void setFtpPassword(String ftpPassword) {
this.ftpPassword = ftpPassword;
}
}