package com.sh.cms.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.SocketException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
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;
public class FtpUtil {
private String path;
private static FTPClient ftpClient;
public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;
public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;
/**
* 方法:connectServer
* 方法說明: 連接ftp服務器
* @param void
* @return FTPClient
*/
public FTPClient connectServer() throws SocketException, IOException {
ftpClient = new FTPClient();
String ipAndPort = "";
String ftpAddress = ftp地址;
String startSub = ftpAddress.substring(0, ftpAddress.indexOf("@"));
String endSub = ftpAddress.substring(ftpAddress.indexOf("@") + 1);
String userPass = startSub.substring(startSub.lastIndexOf("/") + 1);
String[] up = userPass.split(":");
if (endSub.indexOf("/") != -1) {
ipAndPort = endSub.substring(0, endSub.indexOf("/"));
this.path = endSub.substring(endSub.indexOf("/") + 1);
} else {
ipAndPort = endSub;
}
String port;
String ip;
if (ipAndPort.contains(":")) {
ip = ipAndPort.substring(0, ipAndPort.indexOf(":"));
port = ipAndPort.substring(ipAndPort.indexOf(":") + 1);
} else {
ip = ipAndPort;
port = "21";
}
connectServer(ip, Integer.parseInt(port), up[0], up[1]);
return ftpClient;
}
/**
* 方法:connectServer
* 方法說明: 連接ftp服務器
* @param void
* @return FTPClient
*/
public FTPClient connectServer(String server, int port, String user,
String password) throws SocketException, IOException {
ftpClient = new FTPClient();
ftpClient.setConnectTimeout(3000);
ftpClient.setControlEncoding("UTF-8");
ftpClient.connect(server, port);
if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
ftpClient.login(user, password);
} else {
ftpClient.disconnect();
}
ftpClient.enterLocalPassiveMode();
ftpClient.setBufferSize(1024);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
return ftpClient;
}
/**
* 方法:uploadxml
* 方法說明: 向ftp服務器上傳xml文件
* @param input:文件流,fileName:文件名稱
* @return boolean
*/
public boolean uploadxml(InputStream input, String fileName,
String directory) throws Exception {
if (StringUtil.isNotEmpty(this.path)) {
directory = this.path + directory;
}
String[] s = directory.split("/");
for (String p : s) {
if (StringUtil.isNotEmpty(p)) {
boolean staus = ftpClient.changeWorkingDirectory(p);
if (!staus) {
ftpClient.makeDirectory(p);
ftpClient.changeWorkingDirectory(p);
}
}
}
boolean storeFile = ftpClient.storeFile(fileName, input);
input.close();
return storeFile;
}
/**
* 方法:download
* 方法說明: 從ftp服務器下載文件
* @param loadFileName:ftp上文件信息,saveFileName:保存的文件信息
* @return boolean
*/
public boolean download(String loadFileName, String saveFileName)
throws Exception {
FileOutputStream fos = null;
fos = new FileOutputStream(saveFileName);
boolean ss = ftpClient.retrieveFile(loadFileName, fos);
fos.close();
return ss;
}
/**
* 方法:moveFtpDir
* 方法說明: ftp服務器上文件遷移
* @param fromdir:當前文件目錄,todir:要保存的目錄
* @return boolean
*/
public String moveFtpDir(String fromdir, String todir) {
String ftpUrl = null;
try {
DateFormat df = new SimpleDateFormat("yyyyMMdd");
String format = df.format(new Date());
// 判斷當前日期的文件夾是否存在
if (todir != null && !"".equals(todir)) {
FTPFile[] alldirs = ftpClient.listFiles("/");
boolean flgdir = false;
for (int i = 0; i < alldirs.length; i++) {
String dirname = alldirs[i].getName();
if (!dirname.equals(todir.substring(1))) {
continue;
} else {
flgdir = true;
break;
}
}
if (!flgdir) {
ftpClient.makeDirectory(todir + "/");
}
FTPFile[] allFile = ftpClient.listFiles(todir);
boolean flg = false;
for (int i = 0; i < allFile.length; i++) {
String dirname = allFile[i].getName();
if (!dirname.equals(format)) {
continue;
} else {
flg = true;
break;
}
}
if (!flg) {
ftpClient.makeDirectory(todir + "/" + format + "/");
}
}
todir = todir + "/" + format + "/";
// 移動文件
if (fromdir != null && !"".equals(fromdir)) {
FTPFile[] allFile = ftpClient.listFiles(fromdir);
ftpClient
.makeDirectory(todir
+ fromdir.substring(fromdir.lastIndexOf("/") + 1)
+ "/");
todir = todir + fromdir.substring(fromdir.lastIndexOf("/") + 1)
+ "/";
for (int i = 0; i < allFile.length; i++) {
String name = allFile[i].getName();
ftpClient.rename(fromdir + "/" + name, todir + "/" + name);
}
ftpClient.removeDirectory(fromdir);
ftpUrl = todir.substring(0, todir.length() - 1);
}
} catch (IOException e) {
e.printStackTrace();
}
return ftpUrl;
}
/**
* 方法:moveFtpFileToDir
* 方法說明: ftp移動文件到指定目錄
* @param fromdir 從這個文件路徑
* @param fileName 文件名稱
* @param todir 目標路徑
* @return
*/
public String moveFtpFileToDir(String fromdir,String fileName, String todir) {
String ftpUrl = null;
try {
// 移動文件
if (StringUtil.isNotEmpty(fromdir)) {
ftpClient.rename(fromdir + "/" + fileName, todir + "/" + fileName);
ftpUrl = todir.substring(0, todir.length() - Constants.NUMBER_1);
}
} catch (IOException e) {
e.printStackTrace();
}
return ftpUrl;
}
/**
* 方法:downloadFile
* 方法說明: ftp服務器上下載文件
* @param remoteFileName:當前文件名稱,localDires:要保存的目錄,remoteDownLoadPath:ftp上文件目錄
* @return boolean
*/
public boolean downloadFile(String remoteFileName, String localDires,
String remoteDownLoadPath) {
String strFilePath = localDires + remoteFileName;
BufferedOutputStream outStream = null;
boolean success = false;
try {
ftpClient.changeWorkingDirectory(remoteDownLoadPath);
outStream = new BufferedOutputStream(new FileOutputStream(
strFilePath));
success = ftpClient.retrieveFile(remoteFileName, outStream);
if (success == true) {
return success;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != outStream) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (success == false) {
}
return success;
}
/***
* 將下載文件的輸出流轉爲輸入流
* @param remoteFileName 待下載文件名稱
* @param remoteDownLoadPath remoteFileName所在的路徑
* */
public InputStream downloadMetadata(String remoteFileName,
String remoteDownLoadPath) {
InputStream in = null;
try {
ftpClient.changeWorkingDirectory(remoteDownLoadPath);
in = ftpClient.retrieveFileStream(remoteFileName);
return in;
} catch (Exception e) {
e.printStackTrace();
}
return in;
}
/***
* @上傳文件夾
* @param localDirectory
* 當地文件夾
* @param remoteDirectoryPath
* Ftp 服務器路徑 以目錄"/"結束
* */
public boolean uploadDirectory(String localDirectory,
String remoteDirectoryPath) {
File src = new File(localDirectory);
try {
ftpClient.makeDirectory(remoteDirectoryPath);
File[] allFile = src.listFiles();
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (!allFile[currentFile].isDirectory()) {
String srcName = allFile[currentFile].getPath().toString();
uploadFile(new File(srcName), remoteDirectoryPath);
}
}
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (allFile[currentFile].isDirectory()) {
// 遞歸
ftpClient.makeDirectory(remoteDirectoryPath + "/"
+ allFile[currentFile].getName() + "/");
File src2 = new File(allFile[currentFile].getPath());
File[] allFile2 = src2.listFiles();
for (int currentFile2 = 0; currentFile2 < allFile2.length; currentFile2++) {
if (!allFile2[currentFile2].isDirectory()) {
uploadFile(new File(allFile2[currentFile2]
.getPath().toString()), remoteDirectoryPath
+ "/" + allFile[currentFile].getName()
+ "/");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
/***
* 上傳Ftp文件
* @param localFile 當地文件
* @param romotUpLoadePath上傳服務器路徑 - 應該以/結束
* */
public boolean uploadFile(File localFile, String romotUpLoadePath) {
BufferedInputStream inStream = null;
boolean success = false;
try {
this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改變工作路徑
inStream = new BufferedInputStream(new FileInputStream(localFile));
success = this.ftpClient.storeFile(localFile.getName(), inStream);
if (success == true) {
return success;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return success;
}
/***
* 上傳CDN需要的XML文件
* @param tempftpDirectory
* @param filename文件名字
* @param r文件內容
* */
public boolean uploadCDNxmlFile(String filename, String r,
String tempftpDirectory) {
boolean success = false;
InputStream is = null;
try {
// 1.輸入流
is = new ByteArrayInputStream(r.getBytes("utf-8"));
this.ftpClient.changeWorkingDirectory(tempftpDirectory);// 改變工作路徑
success = this.ftpClient.storeFile(filename, is);
if (success == true) {
return success;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return success;
}
/**
*
* 類描述: 刪除FTP上的文件夾
* 參數:
* 返回值: void
* @throws Exception
*/
public void removeDirectoryFtp(String ftpHost, int ftpPort,
String ftpUserName, String ftpPassword, String path) {
FTPClient ftpClient = null;
try {
ftpClient = connectServer(ftpHost, ftpPort, ftpUserName,
ftpPassword);
if (ftpClient.changeWorkingDirectory(path)) {
FTPFile[] files = ftpClient.listFiles();
if (files.length == 0) {
ftpClient.removeDirectory(path);
} else {
for (int i = 0; i < files.length; i++) {
if (files[i].getType() == 0) {
ftpClient.deleteFile(files[i].getName());
} else {
if (files[i].getName().equals("..")
|| files[i].getName().equals(".")) {
continue;
}
removeDirectoryFtp(ftpHost, ftpPort, ftpUserName,
ftpPassword,
path + "/" + files[i].getName());
}
}
ftpClient.removeDirectory(path);
}
}
} catch (final IOException ex) {
ex.printStackTrace();
} finally {
if (ftpClient != null) {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void makeDirectory(String dir) throws IOException {
ftpClient.makeDirectory(dir);
}
/**
* 退出FTP服務器
*
* @throws Exception
*/
public static void EpgFtpLogout() {
try {
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (ftpClient.isConnected()) {
ftpClient.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* @return the ftpClient
*/
public FTPClient getFtpClient() {
return ftpClient;
}
/**
* @param ftpClient the ftpClient to set
*/
public void setFtpClient(FTPClient ftpClient) {
this.ftpClient = ftpClient;
}
}