public class FTPClientUtils {
public static String FTPCONFIG = "config/ftpConfig.properties";
private static String LOCAL_CHARSET = "GBK";
private static FTPClient ftpClient = null; // FTP 客户端代理
// Get FTP config
public static String getFTPSetting(String key) {
String value = "";
Properties prop = new Properties();
try {
prop.load(FTPClientUtils.class.getClassLoader()
.getResourceAsStream("filepath.properties"));
} catch (IOException e) {
logger.info(" ftp 配置文件解析error:", e);
e.printStackTrace();
}
value = prop.getProperty(key).trim();
return value;
}
// open FTP connection,return true=success ,false=failure
public static boolean openConnectFTPService() {
boolean flag = true;
try {
ftpClient = new FTPClient();
//
// ftpClient.setDefaultTimeout(3000);
// //socket超时
// ftpClient.setSoTimeout(5000);
// ftpClient.setBufferSize(524288);
ftpClient.setDefaultPort(Integer
.parseInt(getFTPSetting("ftp.port")));
ftpClient.connect(getFTPSetting("ftp.ip"),
Integer.parseInt(getFTPSetting("ftp.port")));
ftpClient.login(getFTPSetting("ftp.user"),
getFTPSetting("ftp.password"));
// //传输模式和类型
ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// 设定编码格式,让ftp支持中文
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand(
"OPTS UTF8", "ON"))) {
LOCAL_CHARSET = "UTF-8";
}
ftpClient.setControlEncoding(LOCAL_CHARSET);
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
int reply = ftpClient.getReplyCode();
// ftpClient.setDataTimeout(Integer.parseInt(getFTPSetting("ftp.dataTimeOut")));
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
System.err.println("FTP server refused connection.");
logger.info("FTP服务器拒绝连接!");
flag = false;
}
System.err.println("FTP server connection success.");
} catch (SocketException e) {
logger.info("登陆FTP服务器ip:" + getFTPSetting("ftp.ip") + "失败,连接超时.", e);
flag = false;
e.printStackTrace();
} catch (IOException e) {
flag = false;
logger.info("登陆FTP服务器ip:" + getFTPSetting("ftp.ip")
+ "失败,FTP服务器无法打开!", e);
e.printStackTrace();
}
return flag;
}
// close FTP connection
public static void closeConnection() {
try {
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (IOException e) {
logger.info("FTP service close exception:", e);
e.printStackTrace();
}
}
/**
* 列出服务器上所有的文件和目录
*
* @return
*/
public static void ListNamesAll() {
try {
String[] files = ftpClient.listNames();
if (files == null || files.length == 0) {
System.out.println("没有任何文件");
} else {
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static FTPClient getFtpClient() {
return ftpClient;
}
/**
* 列出服务器上所有的文件和目录
*
* @return
*/
public static FTPFile[] getListFiles(String path, final String filterName) {
FTPFile[] ftpFiles = null;
try {
ftpFiles = ftpClient.listFiles(path, new FTPFileFilter() {
@Override
public boolean accept(FTPFile ftpFile) {
String fileName = ftpFile.getName();
if (fileName.startsWith(filterName)) {
return true;
}
return false;
}
});
} catch (IOException e) {
e.printStackTrace();
}
return ftpFiles;
}
public static void mkdir(String path, String dir) throws Exception {
// 切换到文件夹下
ftpClient.changeWorkingDirectory(path);
// 创建远程文件夹
if (dir.contains("/")) {
String[] dirArray = dir.split("/");
for (String d : dirArray) {
if (d != null && !"".equals(d)) {
ftpClient.makeDirectory(dir);
ftpClient.changeWorkingDirectory(d);
}
}
}
}
/**
* 删除一个文件
*/
public static boolean deleteFile(String filename) {
boolean flag = true;
try {
flag = ftpClient.deleteFile(filename);
if (flag) {
System.out.println("删除文件成功!");
} else {
System.out.println("删除文件失败!");
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return flag;
}
/**
* 待定:有问题 删除FTP目录(包括此目录中的所有文件)
*/
public static void deleteDirectory(String pathname) {
try {
openConnectFTPService();
ftpClient.changeWorkingDirectory(pathname);
ftpClient.changeToParentDirectory();// 上一层目录
String[] files = ftpClient.listNames();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
ftpClient.removeDirectory(pathname);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 删除空目录
*/
public static void deleteEmptyDirectory(String pathname) {
try {
openConnectFTPService();
ftpClient.removeDirectory(pathname);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 进入到服务器的某个目录下
*
* @param directory
*/
public static void changeWorkingDirectory(String directory) {
try {
openConnectFTPService();
ftpClient.changeWorkingDirectory(directory);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 返回到上一层目录
*/
public static void changeToParentDirectory() {
try {
openConnectFTPService();
ftpClient.changeToParentDirectory();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* 重命名文件
*
* @param oldFileName
* --原文件名
* @param newFileName
* --新文件名
*/
public static void renameFile(String oldFileName, String newFileName) {
try {
openConnectFTPService();
ftpClient.rename(oldFileName, newFileName);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
/**
* ftp下载
*
* @param remotePath
* @param localPath
* @param videoName
* @return
*/
public static boolean downFile(String remotePath,// FTP服务器文件存放上的相对路径
String localPath,// 下载后文件保存到本地的路径
String videoName// 要下载文件名
) {
boolean flag = false;
FTPClient ftp = new FTPClient();
try {
ftp = new FTPClient();
ftp.connect(getFTPSetting("ftp.ip"),
Integer.parseInt(getFTPSetting("ftp.port")));
ftp.login(getFTPSetting("ftp.user"), getFTPSetting("ftp.password"));
ftp.setFileType(ftp.BINARY_FILE_TYPE); //设置下载文件为二进制模式
ftp.setFileTransferMode(ftp.STREAM_TRANSFER_MODE); ///传输文件为流的形式
if (FTPReply.isPositiveCompletion(ftp.sendCommand("OPTS UTF8", "ON"))) {
LOCAL_CHARSET = "UTF-8";
}
ftp.setControlEncoding(LOCAL_CHARSET);
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return flag;
}
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器图片存放目录
System.out.println("登陆成功,转移到FTP服务器视频存放存放目录"
+ getFTPSetting("ftp.ip") + ":" + getFTPSetting("ftp.port")
+ "/" + remotePath);
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().indexOf(videoName)>=0) {
String parseString = new String(ff.getName().getBytes("UTF-8"),"iso-8859-1");
File localFile = new File(localPath + "/" + ff.getName());
if (localFile.exists()) {
return true;
}
File folder = new File(localPath);
// 如果文件夹不存在则创建
if (!folder.exists() && !folder.isDirectory()) {
System.out.println(folder + "目录不存在、正在创建");
folder.mkdir();
}
OutputStream is = new FileOutputStream(localFile);
ftp.retrieveFile(parseString, is);
System.out.println("下载文件到本地路径" + localPath + "/"
+ ff.getName());
is.close();
}
}
ftp.logout();
flag = true;
}catch (IOException e) {
e.printStackTrace();
System.out.println("FTP下载失败" + e.getMessage());
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
System.out.println("关闭FTP连接失败" + ioe.getMessage());
}
}
}
return flag;
}
/**
* ftp下载
*
* @param remotePath
* @param localPath
* @param videoName
* @return
*/
public static boolean downFileLog(
String remotePath,// FTP服务器文件存放上的相对路径
String localPath,// 下载后文件保存到本地的路径
String videoName// 要下载文件名
) {
boolean flag = false;
FTPClient ftp = new FTPClient();
try {
ftp = new FTPClient();
ftp.connect(getFTPSetting("ftp.ip"),Integer.parseInt(getFTPSetting("ftp.port")));
ftp.login(getFTPSetting("ftp.user"), getFTPSetting("ftp.password"));
ftp.setControlEncoding(LOCAL_CHARSET);
FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
conf.setServerLanguageCode("zh");
int reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return flag;
}
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器图片存放目录
logger.info("登陆成功,转移到FTP服务器视频存放存放目录"+ getFTPSetting("ftp.ip") + ":" + getFTPSetting("ftp.port")+ "/" + remotePath);
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().indexOf(videoName)>=0 || videoName.indexOf(ff.getName())>=0) {
File localFile = new File(localPath);
// 如果文件夹不存在则创建
if (!localFile.exists() && !localFile.isDirectory()) {
logger.info(localPath + "目录不存在、正在创建");
localFile.mkdirs();
}
OutputStream is = new FileOutputStream(localPath + "/"+ ff.getName());
ftp.retrieveFile(ff.getName(), is);
// URL url = new URL("http://172.18.11.76/CGate/qianduan/"+ff.getName());
// downloadFiles(url,localPath+"/"+ff.getName());
is.close();
}
}
ftp.logout();
flag = true;
} catch (IOException e) {
e.printStackTrace();
logger.info("FTP下载失败" + e.getMessage());
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
logger.info("关闭FTP连接失败" + ioe.getMessage());
}
}
}
return flag;
}
public static void downloadFiles(URL theURL, String filePath) throws IOException {
File dirFile = new File(filePath);
if(!dirFile.exists()){
//文件路径不存在时,自动创建目录
dirFile.mkdir();
}
//从服务器上获取文件并保存
URLConnection connection = theURL.openConnection();
InputStream in = connection.getInputStream();
FileOutputStream os = new FileOutputStream(filePath);
byte[] buffer = new byte[4 * 1024];
int read;
while ((read = in.read(buffer)) > 0) {
os.write(buffer, 0, read);
}
os.close();
in.close();
}
/**
* 在服务器上创建一个目录,当当前路径不存在依次创建子目录(文件夹)
*
* @param dir
* 文件夹名称,不能含有特殊字符,如 \ 、/ 、: 、* 、?、 "、 <、>...
*/
public static boolean makeDirectory(String dir) {
openConnectFTPService();
boolean flag = true;
try {
File file = new File(dir);
if (!file.isDirectory()) {
String[] str = dir.split("/");
System.out.println(str.length);
String dirPath = "";
for (int i = 0; i < str.length; i++) {
dirPath += "/" + str[i];
boolean directory = ftpClient
.changeWorkingDirectory(dirPath);
if (!directory) {// 当directory为false,则创建FTP当前路径
flag = ftpClient.makeDirectory(dirPath);
}
}
if (flag) {
System.out.println("make Directory " + dir + " succeed");
} else {
System.out.println("make Directory " + dir + " false");
}
} else {
System.out.println(dir + "不是一个目录");
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 转码[ISO-8859-1 -> GBK] 不同的平台需要不同的转码
*
* @param obj
* @return ""
*/
private static String iso8859togbk(Object obj) {
try {
if (obj == null)
return "";
else
return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
} catch (Exception e) {
return "";
}
}
/**
* 设置传输文件的类型[文本文件或者二进制文件]
*
* @param fileType
* --BINARY_FILE_TYPE、ASCII_FILE_TYPE
*/
public static void setFileType(int fileType) {
try {
ftpClient.setFileType(fileType);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 下载文件
*
* @param remoteFileName
* --服务器上的文件名
* @param localFileName
* --本地文件名
* @return true 下载成功,false 下载失败
*/
public static boolean downloadFile(String remoteFileName,
String localFileName) {
boolean flag = true;
// openConnectFTPService();
// 下载文件
BufferedOutputStream buffOut = null;
try {
flag = ftpClient.retrieveFile(remoteFileName, buffOut);
buffOut = new BufferedOutputStream(new FileOutputStream(
localFileName));
} catch (Exception e) {
e.printStackTrace();
logger.debug("本地文件下载失败!", e);
} finally {
try {
if (buffOut != null)
buffOut.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return flag;
}
/**
* 上传单个文件,并重命名
*
* @param localFile
* --本地文件路径
* @param remoteFileName
* --新的文件名,可以命名为空""
* @param saveRemoteFolderPath
* --FTP服务器上传保存文件夹的路径
* @return true 上传成功,false 上传失败
*/
public static boolean uploadFile(File localFile, String remoteFileName,
String saveRemoteFolderPath) {
boolean flag = true;
try {
InputStream input = new FileInputStream(localFile);
if (input == null) {
return false;
}
openConnectFTPService();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
// 进入FTP当前文件夹,当文件夹不存在则false
boolean remoteFolder = ftpClient
.changeWorkingDirectory(saveRemoteFolderPath);
if (!remoteFolder) {
boolean IsCreatedFolder = makeDirectory(saveRemoteFolderPath);
if (!IsCreatedFolder) {
logger.info(saveRemoteFolderPath + "路径在FTP服务器上面不存在");
System.out.println("路径在FTP服务器上面不存在!");
}
ftpClient.changeWorkingDirectory(saveRemoteFolderPath);
}
flag = ftpClient.storeFile(remoteFileName, input);
if (flag) {
System.out.println("上传文件成功!");
} else {
System.out.println("上传文件失败!");
}
input.close();
} catch (IOException e) {
e.printStackTrace();
logger.debug("本地文件上传失败!", e);
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 上传单个文件,并重命名
*
* @param input
* --文件流
* @param remoteFileName
* --新的文件名,可以命名为空""
* @param saveRemoteFolderPath
* --FTP服务器上传保存文件夹的路径
* @return true 上传成功,false 上传失败
*/
public static boolean inputStreamUploadFile(InputStream input,
String remoteFileName, String saveRemoteFolderPath) {
boolean flag = true;
try {
if (input == null) {
System.out.println("本地文件不存在!");
}
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
// 进入FTP当前文件夹,当文件夹不存在则创建文件夹
boolean remoteFolder = ftpClient
.changeWorkingDirectory(saveRemoteFolderPath);
if (!remoteFolder) {
boolean IsCreatedFolder = makeDirectory(saveRemoteFolderPath);
if (!IsCreatedFolder) {
logger.info(saveRemoteFolderPath + "路径在FTP服务器上面不存在");
System.out.println("路径在FTP服务器上面不存在!");
}
ftpClient.changeWorkingDirectory(saveRemoteFolderPath);
}
flag = ftpClient.storeFile(remoteFileName, input);
if (flag) {
System.out.println("上传文件成功!");
} else {
System.out.println("上传文件失败!");
}
input.close();
} catch (IOException e) {
flag = false;
e.printStackTrace();
logger.debug("本地文件上传失败!", e);
} catch (Exception e) {
flag = false;
e.printStackTrace();
}
return flag;
}
/**
* ftp上传文件
*
* @param f
* @throws Exception
*/
public static boolean upload(File f) {
// 连接FTP
boolean flag = openConnectFTPService();
try {
if (flag) {
if (f.isDirectory()) {
ftpClient.makeDirectory(f.getName());
ftpClient.changeWorkingDirectory(f.getName());
String[] files = f.list();
for (String fstr : files) {
File file1 = new File(f.getPath() + "/" + fstr);
if (file1.isDirectory()) {
upload(file1);
ftpClient.changeToParentDirectory();
} else {
File file2 = new File(f.getPath() + "/" + fstr);
FileInputStream input = new FileInputStream(file2);
ftpClient.storeFile(file2.getName(), input);
input.close();
}
}
} else {
File file2 = new File(f.getPath());
FileInputStream input = new FileInputStream(file2);
ftpClient.storeFile(file2.getName(), input);
input.close();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
flag = false;
e.printStackTrace();
}
return flag;
}
public static void main(String[] args) {
// boolean flag = openConnectFTPService();
// System.out.println(flag);e();
// System.out.println(flag);
boolean flag = false;
try {
openConnectFTPService();
// InputStream input = new FileInputStream("D:\\sql");
File file = new File("D:\\sql");
upload(file);
// flag = inputStreamUploadFile(input, "1.sql","123");
} catch (Exception e) {
e.printStackTrace();
}
// System.out.println(flag);
}
}