import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.StringTokenizer;
public class FTPTool {
protected static Logger logger = LoggerFactory.getLogger(FTPTool.class);
private static FTPClient ftp;
private static String url = "172.17.173.9";
private static int port = 21;
private static String username = "rms";
private static String password = "xccdkj@123";
/**
* 连接FTP服务器
*
* @param serverIp ip地址
* @param serverPort 端口号
* @param serverUserName ftp用户名
* @param serverPassword ftp密码
* @return 是否连接成功
*/
public static boolean connectFtp(String serverIp, int serverPort, String serverUserName, String serverPassword) {
ftp = new FTPClient();
try {
ftp.connect(serverIp, serverPort);
} catch (IOException e) {
e.printStackTrace();
}
try {
ftp = new FTPClient();
ftp.connect(serverIp, serverPort);
ftp.login(serverUserName, serverPassword);
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return false;
}
ftp.setControlEncoding("GBK");//windows系统版本,改为GBK
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
return true;
} catch (Exception e) {
e.printStackTrace();
logger.error("FTP连接失败");
return false;
}
}
/**
* 连接FTP服务器
*
* @param ftpName ftp服务器名称,后期使用
* @return 是否连接陈功
*/
public static boolean connectFtp(String ftpName) {
return connectFtp(url, port, username, password);
}
/**
* 上传文件到FTP服务器
* 使用默认连接
*
* @param localDir 本地目录
* @param localName 本地文件名称
* @param remoteDir 服务器目录
* @param remoteName 服务器名称
* @return 是否上传成功
*/
public static boolean uploadFile(String localDir, String localName, String remoteDir, String remoteName) {
if (!connectFtp(null)) {
return false;
}
File file = new File(localDir + localName);
if (!file.exists() && !file.isFile()) {
logger.debug("本地文件不存在!");
return false;
}
logger.debug("FTP连接成功!");
boolean uploadflag = false;
try {
//中文路径编码和中文文件编码,请忽删除
remoteDir = new String(remoteDir.getBytes("GBK"), "ISO-8859-1");
remoteName = new String(remoteName.getBytes("GBK"), "ISO-8859-1");
FileInputStream input = new FileInputStream(file);
mkDirs(remoteDir, ftp);
//切换FTP工作方式为passive,此行代码很重要。
ftp.enterLocalPassiveMode();
uploadflag = ftp.storeFile(remoteDir + remoteName, input);
int replycode = ftp.getReplyCode();
logger.debug("保存文件如Ftp-Reply:" + replycode);
input.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
return uploadflag;
}
/**
* 默认使用ftp用户
* 从ftp服务器获取指定路径的文件,并保存到本次指定路径
*
* @param localFilePath
* @param remoteFilePath
* @return
*/
public static boolean downloadFile(String localFilePath, String remoteFilePath) {
if (!connectFtp(null)) {
return false;
}
//获取本地目录和远程目录
String localDirectory = null;
String remoteDirectory = null;
String remoteFileName = null;
localDirectory = localFilePath.substring(0, localFilePath.lastIndexOf("."));
localDirectory = localDirectory.substring(0, localDirectory.lastIndexOf("/"));
remoteDirectory = remoteFilePath.substring(0, remoteFilePath.lastIndexOf("."));
remoteDirectory = remoteDirectory.substring(0, remoteDirectory.lastIndexOf("/"));
remoteFileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);
//if(remoteFileName == null || "".equals(remoteFileName)){
// remoteFileName =
//}
boolean downloadflag = false;
try {
File file = new File(localDirectory);
if (!file.exists() && !file.isDirectory()) {
file.mkdir();
}//判断本地目录是否存在,不存在则创建
//ftp.setControlEncoding("GBK");//windows系统版本,改为GBK
ftp.changeWorkingDirectory(remoteDirectory);
FTPFile[] ftpfiles = null;
ftpfiles = ftp.listFiles();
boolean checkflag = false;
for (int i = 0; i < ftpfiles.length; i++) {
if (ftpfiles[i].getName().equals(remoteFileName)) {
downloadflag = downloadFTPFile(ftpfiles[i], localFilePath);
checkflag = true;
break;
}
}
if (!checkflag) {
System.out.println("需要下载的文件FTP服务器上不存在!");
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
return downloadflag;
}
/**
* 下载FTP文件
*
* @param ftpFile
* @param localPath
* @return
*/
private static boolean downloadFTPFile(FTPFile ftpFile, String localPath) {
boolean flag = false;
if (ftpFile.isFile()) {
if (ftpFile.getName().indexOf("?") == -1) {
try {
File localFile = new File(localPath);
//判断本地文件是否存在,存在则返回
if (localFile.exists()) {
localFile.delete();
}
OutputStream outputStream = null;
outputStream = new FileOutputStream(localPath);
String remoteFileName = ftpFile.getName();
//编码格式,请忽修改,此编码针对ftp为windows系统下.文件名称含有中文时用到
flag = ftp.retrieveFile(new String(remoteFileName.getBytes("GBK"), "ISO-8859-1"), outputStream);
outputStream.flush();
outputStream.close();
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
}
} else {
System.out.println("需要下载的目标不是文件!");
}
return flag;
}
/**
* 删除服务器文件
*
* @param remoteFilePath
* @param serverIp
* @param serverPort
* @param userName
* @param password
* @return
*/
public static boolean delFile(String remoteFilePath, String serverIp, int serverPort, String userName, String password) {
if (!connectFtp(serverIp, serverPort, userName, password)) {
return false;
}
//获取远程目录
String remoteDirectory = null;
String remoteFileName = null;
remoteDirectory = remoteFilePath.substring(0, remoteFilePath.lastIndexOf("."));
remoteDirectory = remoteDirectory.substring(0, remoteDirectory.lastIndexOf("/"));
remoteFileName = remoteFilePath.substring(remoteFilePath.lastIndexOf("/") + 1);
boolean deteteflag = false;
try {
FTPFile[] ftpfiles = null;
ftpfiles = ftp.listFiles();
boolean deleteflag = false;
for (int i = 0; i < ftpfiles.length; i++) {
if (ftpfiles[i].getName().equals(remoteFileName)) {
deteteflag = ftp.deleteFile(remoteFilePath);
deleteflag = true;
break;
}
}
if (deleteflag == false) {
System.out.println("需要删除的文件FTP服务器上不存在!");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close();
}
return deteteflag;
}
/**
* 检查目录是否存在
*
* @param dir
* @return
*/
public static boolean isDirExist(String dir, FTPClient client) {
boolean mkResult = false;
try {
mkResult = client.makeDirectory(dir);
} catch (Exception e) {
return false;
}
return mkResult;
}
/**
* 创建层级目录
*/
public static boolean mkDirs(String path, FTPClient client) {
if (null == path) {
return false;
}
try {
client.changeWorkingDirectory("/");// 切换到根目录
StringTokenizer dirs = new StringTokenizer(path, "/");
String temp = null;
boolean flag = false;
while (dirs.hasMoreElements()) {
temp = dirs.nextElement().toString();
if (!isDirExist(temp, client)) {//判断是否存在目录,不存在则创建
flag = true;
}
client.changeWorkingDirectory(temp);
}
if (flag) {
System.out.println(">>>>>create directory:[" + path + "]");
}
client.changeWorkingDirectory("/");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* ftp服务器上复制文件
*
* @param sourceDir 源目录
* @param sourceFileName 源文件名称
* @param targetDir 目标目录
* @param targetFileName 目标文件名称
* @return 是否复制成功
*/
public static boolean copyFile(String sourceDir, String sourceFileName, String targetDir, String targetFileName) {
boolean flag = false;
if (!connectFtp("")) {
return false;
}
try {
mkDirs(targetDir, ftp);
ftp.changeWorkingDirectory(sourceDir);
ByteArrayOutputStream os = new ByteArrayOutputStream();
ByteArrayInputStream in = null;
ftp.retrieveFile(sourceFileName, os);
in = new ByteArrayInputStream(os.toByteArray());
ftp.changeWorkingDirectory(targetDir);
ftp.storeFile(targetFileName, in);
in.close();
flag = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
close();
}
return flag;
}
public static void close() {
if (ftp.isConnected()) {
try {
ftp.logout();
ftp.disconnect();
;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// downloadFile(path, "TSOT23-16R.zip", "D:\\recipe/asm/test");
//uploadFile("D:\\recipe\\asm\\1212.txt","/RECIPE/A8/122/122/", "121.txt","172.17.173.9", "21", "rms", "xccdkj@123");
//uploadFileFromProduction(path, "D:\\recipe\\asm\\TSOT23-16R.zip");
// makeDirectory("/RECIPE/A6/DieAttach");
//copyFile("C:\\tmp\\lrms\\file\\201612", "1481808341166审核人员.txt", "/tmp/lrms/file/201612/", "121审核人员.txt");
//downloadFile("C:/tmp/lrms/file/201612/RCPC中.txt", "/tmp/lrms/file/201612/121审核人员.txt");
//uploadFile("C:/tmp/lrms/file/201612/", "aa.txt", "/tmp/lrms/file/201612中/", "RCPC11中.txt");
FTPTool.downloadFile("C:/tmp/lrms/file/201612/1481869609455google_map.js.txt", "/tmp/lrms/file/201612/1481869609455google_map.js.txt");
System.out.println("==============");
}
}