FTP 上传 下载工具类
一.FTP介绍:
FTP 是File Transfer Protocol(文件传输协议)的英文简称,而中文简称为“文传协议”。用于Internet上的控制文件的双向传输。同时,它也是一个应用程序(Application)。基于不同的操作系统有不同的FTP应用程序,而所有这些应用程序都遵守同一种协议以传输文件。在FTP的使用当中,用户经常遇到两个概念:"下载"(Download)和"上传"(Upload)。"下载"文件就是从远程主机拷贝文件至自己的计算机上;"上传"文件就是将文件从自己的计算机中拷贝至远程主机上。用Internet语言来说,用户可通过客户机程序向(从)远程主机上传(下载)文件。 -- 摘自百度百科
通过JAVA来支持FTP上传或者下载,其实不是太复杂,建立连接,上传,关闭连接,就这样步骤,为了方便以及代码健壮性,当然需要分装一些功能的,但是网也流传着许多工具类,但是其中有些是不行的,大多数都是由于路径的问题,上传多次后就不行了,这里就贴一下工具类,网上download下来,然后修改了一下。
废话不多说,直接上代码了:
import it.sauronsoftware.ftp4j.FTPClient;
import it.sauronsoftware.ftp4j.FTPException;
import it.sauronsoftware.ftp4j.FTPFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.Properties;
import org.springframework.util.StringUtils;
import com.ibm.icu.text.SimpleDateFormat;
/**
* FTP文件处理工具类
* @author yangnuo
*/
public class FTPUtils {
private static FTPUtils ftp;
/**
* FTP服务地址
*/
private static String ADDRESS = "";//PropUtils.getString("ftp_server_address"); http:\\192.168.1.42:21
/**
* FTP登录用户名
*/
private static String USERNAME = ""; //PropUtils.getString("ftp_server_username"); nuohy
/**
* FTP登录密码
*/
private static String PASSWORD = ""; //PropUtils.getString("ftp_server_password"); 123456
/**
* 本地 扫描路径 某个文件夹
*/
private static String PATH = "";
/**
* 构造方法
*/
public FTPUtils() {
initPath();
}
/**
* 实例化对象
*
* @return
*/
public static FTPUtils getInstance() {
if (ftp == null) {
ftp = new FTPUtils();
}
return ftp;
}
/**
* 获取FTP客户端对象
*
* @return
* @throws Exception
*/
public FTPClient getClient() throws Exception {
FTPClient client = new FTPClient();
client.setCharset("utf-8");
client.setType(FTPClient.TYPE_BINARY);
URL url = new URL(FTPUtils.ADDRESS);
int port = url.getPort() < 1 ? 21 : url.getPort();
client.connect(url.getHost(), port);
client.login(FTPUtils.USERNAME, FTPUtils.PASSWORD);
return client;
}
/**
* 注销客户端连接
*
* @param client
* FTP客户端对象
* @throws Exception
*/
public void logout(FTPClient client) throws Exception {
boolean f = true;
if (client == null){
f = true;
}
if (client.isConnected()) {
try {
client.disconnect(true);
f = true;
} catch (Exception e) {
try {
System.out.println("开始强制退出...");
client.disconnect(false);
} catch (Exception e1) {
e1.printStackTrace();
f = false;
}
}
}
/*if (client != null) {
try {
// 有些FTP服务器未实现此功能,若未实现则会出错
client.logout(); // 退出登录
} catch (FTPException fe) {
System.out.println("1推出出现异常,原因:["+fe.getMessage()+"]");
} catch (Exception e) {
System.out.println("2推出出现异常,原因:["+e.getMessage()+"]");
throw e;
} finally {
if (client.isConnected()) { // 断开连接
client.disconnect(true);
}
}
}*/
}
/**
* 创建目录
*
* @param client
* FTP客户端对象
* @param dir
* 目录
* @throws Exception
*/
private void mkdirs(FTPClient client, String dir) throws Exception {
if (dir == null) {
return;
}
dir = dir.replace("//", "/");
String[] dirs = dir.split("/");
for (int i = 0; i < dirs.length; i++) {
dir = dirs[i];
if (!StringUtils.isEmpty(dir)) {
if (!exists(client, dir)) {
client.createDirectory(dir);
}
client.changeDirectory(dir);
}
}
}
/**
* 获取FTP目录
*
* @param url
* 原FTP目录
* @param dir
* 目录
* @return
* @throws Exception
*/
private URL getURL(URL url, String dir) throws Exception {
String path = url.getPath();
if (!path.endsWith("/") && !path.endsWith("//")) {
path += "/";
}
dir = dir.replace("//", "/");
if (dir.startsWith("/")) {
dir = dir.substring(1);
}
path += dir;
return new URL(url, path);
}
/**
* 获取FTP目录
*
* @param dir
* 目录
* @return
* @throws Exception
*/
private URL getURL(String dir) throws Exception {
return getURL(new URL(FTPUtils.ADDRESS), dir);
}
/**
* 判断文件或目录是否存在
*
* @param client
* FTP客户端对象
* @param dir
* 文件或目录
* @return
* @throws Exception
*/
private boolean exists(FTPClient client, String dir) throws Exception {
return getFileType(client, dir) != -1;
}
/**
* 判断当前为文件还是目录
*
* @param client
* FTP客户端对象
* @param dir
* 文件或目录
* @return -1、文件或目录不存在 0、文件 1、目录
* @throws Exception
*/
private int getFileType(FTPClient client, String dir) throws Exception {
FTPFile[] files = null;
try {
files = client.list(dir);
} catch (Exception e) {
return -1;
}
if (files.length > 1) {
return FTPFile.TYPE_DIRECTORY;
} else if (files.length == 1) {
FTPFile f = files[0];
if (f.getType() == FTPFile.TYPE_DIRECTORY) {
return FTPFile.TYPE_DIRECTORY;
}
String path = dir + "/" + f.getName();
try {
int len = client.list(path).length;
if (len == 1) {
return FTPFile.TYPE_DIRECTORY;
} else {
return FTPFile.TYPE_FILE;
}
} catch (Exception e) {
return FTPFile.TYPE_FILE;
}
} else {
try {
client.changeDirectory(dir);
client.changeDirectoryUp();
return FTPFile.TYPE_DIRECTORY;
} catch (Exception e) {
return -1;
}
}
}
/**
* 上传文件或目录
*
* @param dir
* 目标文件
* @param del
* 是否删除源文件,默认为false
* @param file
* 文件或目录对象数组
* @throws Exception
*/
public void upload(String dir, boolean del, File... files) throws Exception {
if (StringUtils.isEmpty(dir) || StringUtils.isEmpty(files)) {
return;
}
FTPClient client = null;
try {
client = getClient();
if(IsCreateDir(dir)){
mkdirs(client, dir); // 创建文件
}
client.changeDirectory(dir);
for (File file : files) {
if (file.isDirectory()) { // 上传目录
uploadFolder(client, getURL(dir), file, del);
} else {
client.upload(file); // 上传文件
if (del) { // 删除源文件
file.delete();
}
}
}
} finally {
logout(client);
}
}
/**
* 上传文件或目录
*
* @param dir
* 目标文件
* @param files
* 文件或目录对象数组
* @throws Exception
*/
public void upload(String dir, File... files) throws Exception {
upload(dir, false, files);
}
/**
* 上传文件或目录
*
* @param dir
* 目标文件
* @param del
* 是否删除源文件,默认为false
* @param path
* 文件或目录路径数组
* @throws Exception
*/
public void upload(String dir, boolean del, String[] paths)throws Exception {
if (StringUtils.isEmpty(paths)) {
return;
}
File[] files = new File[paths.length];
for (int i = 0; i < paths.length; i++) {
files[i] = new File(paths[i]);
}
upload(dir, del, files);
}
/**
* 上传文件或目录
*
* @param dir
* 目标文件
* @param paths
* 文件或目录路径数组
* @throws Exception
*/
public void upload(String dir, String... paths) throws Exception {
upload(dir, false, paths);
}
/**
* 上传目录
*
* @param client
* FTP客户端对象
* @param parentUrl
* 父节点URL
* @param file
* 目录
* @throws Exception
*/
private void uploadFolder(FTPClient client, URL parentUrl, File file,
boolean del) throws Exception {
client.changeDirectory(parentUrl.getPath());
String dir = file.getName(); // 当前目录名称
URL url = getURL(parentUrl, dir);
if (!exists(client, url.getPath())) { // 判断当前目录是否存在
client.createDirectory(dir); // 创建目录
}
client.changeDirectory(dir);
File[] files = file.listFiles(); // 获取当前文件夹所有文件及目录
for (int i = 0; i < files.length; i++) {
file = files[i];
if (file.isDirectory()) { // 如果是目录,则递归上传
uploadFolder(client, url, file, del);
} else { // 如果是文件,直接上传
client.changeDirectory(url.getPath());
client.upload(file);
if (del) { // 删除源文件
file.delete();
}
}
}
}
/**
* 删除文件或目录
*
* @param dir
* 文件或目录数组
* @throws Exception
*/
public void delete(String... dirs) throws Exception {
if (StringUtils.isEmpty(dirs)) {
return;
}
FTPClient client = null;
try {
client = getClient();
int type = -1;
for (String dir : dirs) {
client.changeDirectory("/"); // 切换至根目录
type = getFileType(client, dir); // 获取当前类型
if (type == 0) { // 删除文件
client.deleteFile(dir);
} else if (type == 1) { // 删除目录
deleteFolder(client, getURL(dir));
}
}
} finally {
logout(client);
}
}
/**
* 删除目录
*
* @param client
* FTP客户端对象
* @param url
* FTP URL
* @throws Exception
*/
private void deleteFolder(FTPClient client, URL url) throws Exception {
String path = url.getPath();
client.changeDirectory(path);
FTPFile[] files = client.list();
String name = null;
for (FTPFile file : files) {
name = file.getName();
// 排除隐藏目录
if (".".equals(name) || "..".equals(name)) {
continue;
}
if (file.getType() == FTPFile.TYPE_DIRECTORY) { // 递归删除子目录
deleteFolder(client, getURL(url, file.getName()));
} else if (file.getType() == FTPFile.TYPE_FILE) { // 删除文件
client.deleteFile(file.getName());
}
}
client.changeDirectoryUp();
client.deleteDirectory(url.getPath()); // 删除当前目录
}
/**
* 下载文件或目录
*
* @param localDir
* 本地存储目录
* @param dirs
* 文件或者目录
* @throws Exception
*/
public void download(String localDir, String... dirs) throws Exception {
if (StringUtils.isEmpty(dirs)) {
return;
}
FTPClient client = null;
try {
client = getClient();
File folder = new File(localDir);
if (!folder.exists()) { // 如果本地文件夹不存在,则创建
folder.mkdirs();
}
int type = -1;
String localPath = null;
for (String dir : dirs) {
client.changeDirectory("/"); // 切换至根目录
type = getFileType(client, dir); // 获取当前类型
if (type == 0) { // 文件
localPath = localDir + "/" + new File(dir).getName();
client.download(dir, new File(localPath));
} else if (type == 1) { // 目录
downloadFolder(client, getURL(dir), localDir);
}
}
} finally {
logout(client);
}
}
/**
* 下载文件夹
*
* @param client
* FTP客户端对象
* @param url
* FTP URL
* @param localDir
* 本地存储目录
* @throws Exception
*/
private void downloadFolder(FTPClient client, URL url, String localDir) throws Exception {
String path = url.getPath();
client.changeDirectory(path);
// 在本地创建当前下载的文件夹
File folder = new File(localDir + "/" + new File(path).getName());
if (!folder.exists()) {
folder.mkdirs();
}
localDir = folder.getAbsolutePath();
FTPFile[] files = client.list();
String name = null;
for (FTPFile file : files) {
name = file.getName();
// 排除隐藏目录
if (".".equals(name) || "..".equals(name)) {
continue;
}
if (file.getType() == FTPFile.TYPE_DIRECTORY) { // 递归下载子目录
downloadFolder(client, getURL(url, file.getName()), localDir);
} else if (file.getType() == FTPFile.TYPE_FILE) { // 下载文件
client.download(name, new File(localDir + "/" + name));
}
}
client.changeDirectoryUp();
}
/**
* 获取目录下所有文件
*
* @param dir
* 目录
* @return
* @throws Exception
*/
public String[] list(String dir) throws Exception {
FTPClient client = null;
try {
client = getClient();
client.changeDirectory(dir);
String[] values = client.listNames();
if (values != null) {
// 将文件排序(忽略大小写)
Arrays.sort(values, new Comparator<String>(){
public int compare(String val1, String val2) {
return val1.compareToIgnoreCase(val2);
}
});
}
return values;
} catch(FTPException fe) {
// 忽略文件夹不存在的情况
String mark = "code=550";
if (fe.toString().indexOf(mark) == -1) {
throw fe;
}
} finally {
logout(client);
}
return new String[0];
}
/**
* 判断是否存在文件夹
* @param dir
* @return
*/
public boolean IsCreateDir(String dir){
FTPClient client = null;
boolean f = false;
try {
client = getClient();
try {
client.changeDirectory(dir);
client.changeDirectoryUp();
}catch (Exception e) {
f = true;
}
} catch (Exception e) {
}finally{
try {
logout(client);
} catch (Exception e) {
System.out.println("判断是否存在文件夹时,关闭连接失败!");
}
}
System.out.println("能否创建文件夹:"+f);
return f;
}
/**
* 初始化路径
*/
public void initPath(){
if(!PATH.equals("")&&!ADDRESS.equals("")&&!USERNAME.equals("")&&!PASSWORD.equals("")){
return;
}
System.out.println("加载路径");
InputStream in = this.getClass().getResourceAsStream("/App.properties");
Properties prop = new Properties();
try {
prop.load(in);
} catch (IOException e) {
e.printStackTrace();
System.out.println("读取配置文件失败!");
}
PATH = prop.getProperty("scanpath");
ADDRESS = prop.getProperty("address");
USERNAME = prop.getProperty("username");
PASSWORD = prop.getProperty("password");
}
/**
* 获取文件夹下 所有的文件路径
* @param path
* @return
*/
public String[] getFilePath(String path){
System.out.println("======");
if(path==null||path.equals("")){
System.out.println("PATH:"+PATH);
path = PATH;
}
String[] refilepath = new String[0];
try{
File file = new File(path);
File[] listFiles = file.listFiles();
for (File f : listFiles) {
if(f.isFile()){
String filename = f.getName();
String[] split = filename.split("_");
String timestr = split[1];
timestr = timestr.substring(0, 8);
int currentTime = Integer.parseInt(new SimpleDateFormat("yyyyMMdd").format(new Date()));
// System.out.println("split.length>"+split.length);
//只备份昨天的 数据
if(Integer.parseInt(timestr)==currentTime-1&&split.length==2){
refilepath = Arrays.copyOf(refilepath, refilepath.length+1);
refilepath[refilepath.length-1] = f.getAbsolutePath();
}
}
}
}catch(Exception e){
e.printStackTrace();
System.out.println("获取路径失败!");
}
return refilepath;
}
/**
* 修改文件名字
* @return
*/
public boolean editFileName(String filepath,String newFileName){
try{
File file = new File(filepath);
file.renameTo(new File(file.getParent()+File.separator+newFileName));
// System.out.println("将"+file.getName()+"文件, 重命名为:"+newFileName);
// System.out.println("新文件路径:"+file.getParent()+File.separator+newFileName);
}catch(Exception e){
return false;
}
return true;
}
}
然后 直接调用 进行上传
FTPUtils ftpUtils = new FTPUtils();
//获取被扫描文件夹下所有符合上传条件的文件路径
String[] filePath = ftpUtils.getFilePath(null);
for (String string : filePath) {
File editfilename = new File(string);
try {
ftpUtils.upload("sql", new String[]{string});
System.out.println(editfilename.getName()+"上传完成!");
} catch (Exception e) {
System.out.println(editfilename.getName()+"上传失败! 原因:["+e.getMessage()+"]");
e.printStackTrace();
}
if(ftpUtils.editFileName(string, editfilename.getName().split("\\.")[0]+"_1"+".sql")){
System.out.println("完成修改文件名!");
}
}
其中 ftpUtils.getFilePath(null); 这个方法是获取某个文件夹下的所有.sql文件路径+名称的,传入空值,表示使用配置的路径。获取到的文件名称类似为,xxx_20170224170400.sql,如果想要上传其他的文件,只要改动这个方法即可。
配置文件为 App.properties
#需要上传文件的上级文件夹
scanpath=C\:/Users/admin/Desktop/ss/
#ftp服务器地址
address=http\://192.168.1.42:21
#用户名
username=root
#密码
password=123456