java FTP 工具类 同步文件夹 下载文件..等操作(FtpHelper 需要commons-net-3.5.jar)

简介: package com.esb.component; import java.io.BufferedOutputStream; import java.
package com.esb.component;


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPFileFilter;
import org.apache.commons.net.ftp.FTPReply;
/*import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
*/
public class FtpHelper {


private FTPClient ftp = null;
/**
* Ftp服务器
*/
private String server;
/**
* 用户名
*/
private String uname;
/**
* 密码
*/
private String password;
/**
* 连接端口,默认21
*/
private int port = 21;

//private Document document ;


public FtpHelper(String server, int port, String uname,
String password){
this.server = server;
if (this.port > 0){
this.port = port;
}
this.uname = uname;
this.password = password;
//初始化
ftp = new FTPClient();
}
/**
* 连接FTP服务器
* 
* @param server
* @param uname
* @param password
* @return
* @throws Exception
*/
public FTPClient connectFTPServer() throws Exception {
try {
ftp.setControlEncoding("GBK");
//ftp.setControlEncoding("UTF-8");

ftp.configure(getFTPClientConfig());
ftp.connect(this.server, this.port);
if (!ftp.login(this.uname, this.password)) {
ftp.logout();
ftp = null;
return ftp;
}


// 文件类型,默认是ASCII
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

// 设置被动模式
ftp.enterLocalPassiveMode();
ftp.setConnectTimeout(10000);
ftp.setBufferSize(1024);
// 响应信息
int replyCode = ftp.getReplyCode();
if ((!FTPReply.isPositiveCompletion(replyCode))) {
// 关闭Ftp连接
closeFTPClient();
// 释放空间
ftp = null;
throw new Exception("登录FTP服务器失败,请检查![Server:" + server + "、"
+ "User:" + uname + "、" + "Password:" + password);
} else {
return ftp;
}
} catch (Exception e) {
ftp.disconnect();
ftp = null;
throw e;
}
}


/**
* 配置FTP连接参数
* 
* @return
* @throws Exception
*/
public FTPClientConfig getFTPClientConfig() throws Exception {
String systemKey = FTPClientConfig.SYST_UNIX;//FTPClientConfig.SYST_NT;
String serverLanguageCode = "zh";
FTPClientConfig conf = new FTPClientConfig(systemKey);
conf.setServerLanguageCode(serverLanguageCode);
conf.setDefaultDateFormatStr("yyyy-MM-dd");
return conf;
}


/**
* 向FTP根目录上传文件
* 
* @param localFile
* @param newName
*            新文件名
* @throws Exception
*/
public Boolean uploadFile(String localFile, String newName)
throws Exception {
InputStream input = null;
boolean success = false;
try {
File file = null;
if (checkFileExist(localFile)) {
file = new File(localFile);
}
input = new FileInputStream(file);
success = ftp.storeFile(newName, input);
if (!success) {
throw new Exception("文件上传失败!");
}
} catch (Exception e) {
throw e;
} finally {
if (input != null) {
input.close();
}
}
return success;
}


/**
* 向FTP根目录上传文件
* 
* @param input
* @param newName
*            新文件名
* @throws Exception
*/
public Boolean uploadFile(InputStream input, String newName)
throws Exception {
boolean success = false;
try {
success = ftp.storeFile(newName, input);
if (!success) {
throw new Exception("文件上传失败!");
}
} catch (Exception e) {
throw e;
} finally {
if (input != null) {
input.close();
}
}
return success;
}


/**
* 向FTP指定路径上传文件
* 
* @param localFile
* @param newName
*            新文件名
* @param remoteFoldPath
* @throws Exception
*/
public Boolean uploadFile(String localFile, String newName,
String remoteFoldPath) throws Exception {


InputStream input = null;
boolean success = false;
try {
File file = null;
if (checkFileExist(localFile)) {
file = new File(localFile);
}
input = new FileInputStream(file);


// 改变当前路径到指定路径
if (!this.changeDirectory(remoteFoldPath)) {
System.out.println("服务器路径不存!");
return false;
}
success = ftp.storeFile(newName, input);
if (!success) {
throw new Exception("文件上传失败!");
}
} catch (Exception e) {
throw e;
} finally {
if (input != null) {
input.close();
}
}
return success;
}


/**
* 向FTP指定路径上传文件
* 
* @param input
* @param newName
*            新文件名
* @param remoteFoldPath
* @throws Exception
*/
public Boolean uploadFile(InputStream input, String newName,
String remoteFoldPath) throws Exception {
boolean success = false;
try {
// 改变当前路径到指定路径
if (!this.changeDirectory(remoteFoldPath)) {
System.out.println("服务器路径不存!");
return false;
}
success = ftp.storeFile(newName, input);
if (!success) {
throw new Exception("文件上传失败!");
}
} catch (Exception e) {
throw e;
} finally {
if (input != null) {
input.close();
}
}
return success;
}
/**
* 从FTP服务器下载文件
* 
* @param remotePath
*            FTP路径(不包含文件名)
* @param fileName
*            下载文件名
* @param localPath
*            本地路径
*/
public Boolean downloadFile(String remotePath, String fileName,
String localPath) throws Exception {
Date begin=new Date();
BufferedOutputStream output = null;
boolean success = false;
try {
File dir =new File(localPath);
if(!dir.exists())
dir.mkdirs();

// 检查本地路径
this.checkFileExist(localPath);
// 改变工作路径
if (!this.changeDirectory(remotePath)) {
System.out.println("当前路径 "+ftp.printWorkingDirectory()+" 服务器路径"+remotePath+"不存在");
return false;
}
// 列出当前工作路径下的文件列表
List<FTPFile> fileList = this.getFileList();
if (fileList == null || fileList.size() == 0) {
System.out.println("服务器当前路径下不存在文件!");
return success;
}


File localFilePath = new File(localPath + File.separator
+ fileName);
output = new BufferedOutputStream(new FileOutputStream(
localFilePath));
success = ftp.retrieveFile(fileName, output);
if(!success){
System.err.println("文件下载失败:"+remotePath+" "+fileName);
}else{
System.out.println("下载成功 (耗时:"+(System.currentTimeMillis()-begin.getTime())/1000d+" s):"+remotePath+"/"+fileName+"-> "+localPath+"/"+fileName);
}

/*for (FTPFile ftpfile : fileList) {
String ftpFileName=ftpfile.getName();
if (ftpFileName.equals(fileName)) {
File localFilePath = new File(localPath + File.separator
+ ftpFileName);
output = new BufferedOutputStream(new FileOutputStream(
localFilePath));
success = ftp.retrieveFile(ftpFileName, output);
if(!success){
System.err.println("文件下载失败:"+remotePath+" "+fileName);
}
}else{
System.err.println("ftpFileName.equals(fileName) 不匹配 "+ftpFileName+" "+fileName);
}
}*/
/*if (!success) {
throw new Exception("文件下载失败!");
}*/
} catch (Exception e) {
throw e;
} finally {
if (output != null) {
output.close();
}
}
return success;
}


/**
* 从FTP服务器获取文件流
* 
* @param remoteFilePath
* @return
* @throws Exception
*/
public InputStream downloadFile(String remoteFilePath) throws Exception {


return ftp.retrieveFileStream(remoteFilePath);
}


/**
* 获取FTP服务器上指定路径下的文件列表
* 
* @param filePath
* @return
*/
/*
public List<FTPFile> getFtpServerFileList(String remotePath)
throws Exception {


FTPListParseEngine engine = ftp.initiateListParsing(remotePath);
List<FTPFile> ftpfiles = Arrays.asList(engine.getNext(25));


return ftpfiles;
}*/


/**
* 获取FTP服务器上[指定路径]下的文件列表
* 
* @param path
* @return
* @throws Exception
*/
public List<FTPFile> getFileList(String remotePath) throws Exception {
if(remotePath!=null && !remotePath.endsWith("/")){
remotePath+="/";
}
List<FTPFile> ftpfiles = Arrays.asList(ftp.listFiles(remotePath,new FTPFileFilter() {
@Override
public boolean accept(FTPFile f) {
/*if(remotePath2!=null && remotePath2.equals(f.getName()) && f.getType()==FTPFile.DIRECTORY_TYPE){
return false;
}*/
if(".".equals(f.getName()) || "..".equals(f.getName())){
return false;
}
return true;
}
}));


return ftpfiles;
}


/**
* 获取FTP服务器[当前工作路径]下的文件列表
* 
* @param path
* @return
* @throws Exception
*/
public List<FTPFile> getFileList() throws Exception {


List<FTPFile> ftpfiles = Arrays.asList(ftp.listFiles(null,new FTPFileFilter() {
@Override
public boolean accept(FTPFile f) {
if(!".".equals(f.getName()) && !"..".equals(f.getName())){
return true;
}
return false;
}
}));

return ftpfiles;
}


/**
* 改变FTP服务器工作路径 
* 
* @param remoteFoldPath
*/
public Boolean changeDirectory(String remoteFoldPath) throws Exception {


return ftp.changeWorkingDirectory(remoteFoldPath);
}


/**
* 删除文件
* 
* @param remoteFilePath
* @return
* @throws Exception
*/
public Boolean deleteFtpServerFile(String remoteFilePath) throws Exception {


return ftp.deleteFile(remoteFilePath);
}


/**
* 创建目录
* 
* @param remoteFoldPath
* @return
*/
public boolean createFold(String remoteFoldPath) throws Exception {


boolean flag = ftp.makeDirectory(remoteFoldPath);
if (!flag) {
throw new Exception("创建目录失败");
}
return false;
}


/**
* 删除目录
* @param remoteFoldPath
* @return
* @throws Exception
*/
public boolean deleteFold(String remoteFoldPath) throws Exception {

return ftp.removeDirectory(remoteFoldPath) ;
}


/**
* 删除目录以及文件
* 
* @param remoteFoldPath
* @return
*/
public boolean deleteFoldAndsubFiles(String remoteFoldPath)
throws Exception {


boolean success = false;
List<FTPFile> list = this.getFileList(remoteFoldPath);
if (list == null || list.size() == 0) {
return deleteFold(remoteFoldPath);
}
for (FTPFile ftpFile : list) {

String name = ftpFile.getName();
if (ftpFile.isDirectory()) {
success = deleteFoldAndsubFiles(remoteFoldPath + "/" + name);
if (!success)
break;
} else {
success = deleteFtpServerFile(remoteFoldPath + "/" + name);
if (!success)
break;
}
}
if (!success)
return false;
success = deleteFold(remoteFoldPath);
return success;
}


/**
* 检查本地路径是否存在
* 
* @param filePath
* @return
* @throws Exception
*/
public boolean checkFileExist(String filePath) throws Exception {
boolean flag = false;
File file = new File(filePath);
if (!file.exists()) {
throw new Exception("本地路径不存在,请检查!");
} else {
flag = true;
}
return flag;
}

/**
* 创建XML文件
* @return
*/
/*public Element getCurrentElement(){
document = DocumentHelper.createDocument();
return document.addElement("root");
}*/

/**
* 生成目录XML文件
*/
/*public void createDirectoryXML(String remotePath,Element fatherElement) throws Exception{


List<FTPFile> list = this.getFileList();
for(FTPFile ftpfile:list){
Element currentElement = fatherElement; //当前的目录节点
String newRemotePath = remotePath+ftpfile.getName();
if(ftpfile.isDirectory()){
Element dirElement = fatherElement.addElement("dir") ;
dirElement.addAttribute("name",ftpfile.getName());
currentElement = dirElement;
this.changeDirectory(newRemotePath); //从根目录开始
createDirectoryXML(newRemotePath,dirElement);
}else{
Element fileElement = fatherElement.addElement("file");//文件节点
fileElement.setText(ftpfile.getName()) ;
}
}
}*/

/**
* 保存xml
*/
/*public void saveXML(){
XMLWriter output = new XMLWriter();
        //输出格式化
        OutputFormat format = OutputFormat.createPrettyPrint();
        try {
            output = new XMLWriter(new FileWriter("src/com/shine/Ftp/config/dir.xml"), format);
            output.write(this.document);
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
}*/

/**
* 关闭FTP连接
* 
* @param ftp
* @throws Exception
*/
public void closeFTPClient(FTPClient ftp) throws Exception {


try {
if (ftp.isConnected())
ftp.logout();
ftp.disconnect();
} catch (Exception e) {
throw new Exception("关闭FTP服务出错!");
}
}


/**
* 关闭FTP连接
* 
* @throws Exception
*/
public void closeFTPClient() throws Exception {


this.closeFTPClient(this.ftp);
}


/**
* Get Attribute Method
* 
*/
public FTPClient getFtp() {
return ftp;
}


public String getServer() {
return server;
}


public String getUname() {
return uname;
}


public String getPassword() {
return password;
}


public int getPort() {
return port;
}


/**
* Set Attribute Method
* 
*/
public void setFtp(FTPClient ftp) {
this.ftp = ftp;
}


public void setServer(String server) {
this.server = server;
}


public void setUname(String uname) {
this.uname = uname;
}


public void setPassword(String password) {
this.password = password;
}


public void setPort(int port) {
this.port = port;
}

public int synFtpFolder(String remotePath,String localPath) throws Exception{
if(remotePath==null){
remotePath="/";
}else if(!remotePath.startsWith("/")){
remotePath="/"+remotePath;
}

List<FTPFile> lst=getFileList(remotePath);
int fileCount=0;
System.out.println("同步文件夹:" +remotePath+" "+lst.size());
for(int i=0;i<lst.size();i++){
FTPFile f=lst.get(i);
if(f.getType()==FTPFile.DIRECTORY_TYPE){
fileCount+=synFtpFolder((remotePath=="/"?"":remotePath)+"/"+f.getName(),localPath+"/"+f.getName());
}else if(f.getType()==FTPFile.FILE_TYPE){
System.out.println("同步文件:"+remotePath+"/"+f.getName()+"  ");
File dir=new File(localPath);
if(!dir.exists()){
dir.mkdirs();
}

downloadFile(remotePath, f.getName(), localPath);
fileCount++;
}else{
System.out.println("ftp文件 特殊类型"+f.getType());
}
}
return fileCount;
}
public List<FTPFile> getAllFiles(String remotePath) throws Exception{
Date begin=new Date();
if(remotePath==null){
remotePath="/";
}else if(!remotePath.startsWith("/")){
remotePath="/"+remotePath;
}
List<FTPFile> files=new ArrayList<>();
List<FTPFile> lst=getFileList(remotePath);
for(int i=0;i<lst.size();i++){
FTPFile f=lst.get(i);
if(f.getType()==FTPFile.DIRECTORY_TYPE){
files.addAll(getAllFiles((remotePath=="/"?"":remotePath)+"/"+f.getName()));
}else if(f.getType()==FTPFile.FILE_TYPE){
files.add(f);
}else{
System.out.println("ftp文件 特殊类型"+f.getType());
}
}
System.out.println("遍历"+remotePath+" 耗时 "+(System.currentTimeMillis()-begin.getTime())/1000d+" s");
return files;
}
/**
* 主方法(测试)
* 
* 问题:上传时命名的新文件名不能有中文,否则上传失败.
* 
* @param args
* @throws Exception 
*/
public static void main(String[] args) throws Exception {
/*try {
FtpHelper fu = new FtpHelper("192.168.2.18", 21, "administrator","sunshine");
fu.connectFTPServer();
Element fatherElement = fu.getCurrentElement();
fu.createDirectoryXML("/", fatherElement);
fu.saveXML();
} catch (Exception e) {
System.out.println("异常信息:" + e.getMessage());
}*/

FtpHelper fu = new FtpHelper("192.168.1.137", 88, "HoPacs","cnhis");
//FtpHelper fu = new FtpHelper("192.168.1.213", 88, "martin","martin");
fu.connectFTPServer();

//fu.do"ftp://HoPacs:cnhis@192.168.1.137:88/RisImgDir/2016-06-21/US0000000001/US0000000001.jpg"

/*fu.changeDirectory("RisImgDir/2013-11-27/US0000000013");

List<FTPFile> lst=fu.getFileList();
System.out.println(lst.size());
for(int i=0;i<lst.size();i++){
FTPFile f=lst.get(i);

System.out.println("类型:"+f.getType()+"  "+f);
if(f.getType()==FTPFile.DIRECTORY_TYPE){

}else if(f.getType()==FTPFile.FILE_TYPE){
fu.downloadFile("/RisImgDir/2013-11-27/US0000000013", f.getName(), "D:/workspace/testFTP/ftp");
}else{
System.out.println("ftp文件 特殊类型"+f.getType());
}
}*/

//同步文件夹
/* 
int count=fu.synFtpFolder("/2015-08-18","D:/workspace/testFTP/ftp");
System.out.println("文件同步总数量"+count);*/

//遍历根目录
List<FTPFile> allFiles=fu.getAllFiles(null);
for(FTPFile f: allFiles){
System.out.println(f.getName()+" "+(f.getTimestamp()==null?null:f.getTimestamp().getTime().toLocaleString()));
}

//fu.downloadFile("/test","《技术服务部制度》修订版V1.4.pdf","D:/workspace/testFTP/ftp/localftp") ;


//fu.downloadFile("/21877","《技术服务部制度》修订版V1.4.pdf","D:/workspace/testFTP/ftp") ;

/*for(FTPFile f: fu.getFileList("/21877")){
System.out.println(f.getName());
}*/

/*fu.changeDirectory("/2012-07-11/US0000000009");
System.out.println(fu.getFileList("/").size());*/

/*fu.changeDirectory("/2012-07-11/US0000000009");
boolean b=fu.changeDirectory("/2012-07-11/US0000000009");
System.out.println("存在目录? "+b);*/

fu.closeFTPClient();
}
}

目录
相关文章
|
C++ Windows
.NET Framework安装不成功,下载`NET Framework 3.5`文件,Microsoft Visual C++
.NET Framework常见问题及解决方案汇总,涵盖缺失组件、安装失败、错误代码等,提供多种修复方法,包括全能王DLL修复工具、微软官方运行库及命令行安装等,适用于Windows系统,解决应用程序无法运行问题。
1906 3
|
Java Unix Go
【Java】(8)Stream流、文件File相关操作,IO的含义与运用
Java 为 I/O 提供了强大的而灵活的支持,使其更广泛地应用到文件传输和网络编程中。!但本节讲述最基本的和流与 I/O 相关的功能。我们将通过一个个例子来学习这些功能。
491 1
|
监控 Java API
Java语言按文件创建日期排序及获取最新文件的技术
这段代码实现了文件创建时间的读取、文件列表的获取与排序以及获取最新文件的需求。它具备良好的效率和可读性,对于绝大多数处理文件属性相关的需求来说足够健壮。在实际应用中,根据具体情况,可能还需要进一步处理如访问权限不足、文件系统不支持某些属性等边界情况。
671 14
|
存储 Java 数据安全/隐私保护
Java技术栈揭秘:Base64加密和解密文件的实战案例
以上就是我们今天关于Java实现Base64编码和解码的实战案例介绍。希望能对你有所帮助。还有更多知识等待你去探索和学习,让我们一同努力,继续前行!
1047 5
|
前端开发 Cloud Native Java
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
博客不应该只有代码和解决方案,重点应该在于给出解决方案的同时分享思维模式,只有思维才能可持续地解决问题,只有思维才是真正值得学习和分享的核心要素。如果这篇博客能给您带来一点帮助,麻烦您点个赞支持一下,还可以收藏起来以备不时之需,有疑问和错误欢迎在评论区指出~
Java||Springboot读取本地目录的文件和文件结构,读取服务器文档目录数据供前端渲染的API实现
|
存储 Java 编译器
深入理解Java虚拟机--类文件结构
本内容介绍了Java虚拟机与Class文件的关系及其内部结构。Class文件是一种与语言无关的二进制格式,包含JVM指令集、符号表等信息。无论使用何种语言,只要能生成符合规范的Class文件,即可在JVM上运行。文章详细解析了Class文件的组成,包括魔数、版本号、常量池、访问标志、类索引、字段表、方法表和属性表等,并说明其在Java编译与运行过程中的作用。
477 0
|
存储 人工智能 Java
java之通过Http下载文件
本文介绍了使用Java实现通过文件链接下载文件到本地的方法,主要涉及URL、HttpURLConnection及输入输出流的操作。
944 0
|
存储 算法 Java
解锁“分享文件”高效密码:探秘 Java 二叉搜索树算法
在信息爆炸的时代,文件分享至关重要。二叉搜索树(BST)以其高效的查找性能,为文件分享优化提供了新路径。本文聚焦Java环境下BST的应用,介绍其基础结构、实现示例及进阶优化。BST通过有序节点快速定位文件,结合自平衡树、多线程和权限管理,大幅提升文件分享效率与安全性。代码示例展示了文件插入与查找的基本操作,适用于大规模并发场景,确保分享过程流畅高效。掌握BST算法,助力文件分享创新发展。
|
网络协议 安全 Java
实现Java语言的文件断点续传功能的技术方案。
像这样,我们就完成了一项看似高科技、实则亲民的小工程。这样的技术实现不仅具备实用性,也能在面对网络不稳定的挑战时,稳稳地、不失乐趣地完成工作。
693 0
|
存储 缓存
.NET 6中Startup.cs文件注入本地缓存策略与服务生命周期管理实践:AddTransient, AddScoped, AddSingleton。
记住,选择正确的服务生命周期并妥善管理它们是至关重要的,因为它们直接影响你的应用程序的性能和行为。就像一个成功的建筑工地,工具箱如果整理得当,工具选择和使用得当,工地的整体效率将会大大提高。
506 0

热门文章

最新文章