java ftp递归下载文件_ftp下载目录下所有文件及文件夹内(递归)

这个博客介绍了一个`FTPHelper`类,用于Java中实现FTP的上传和下载功能,包括递归下载FTP服务器上的整个目录及其子文件夹。类提供了连接FTP服务器、上传文件、下载文件和断点续传的方法。此外,还有列出FTP目录中的文件和目录、判断文件列表样式以及根据样式解析文件信息的功能。
摘要由CSDN通过智能技术生成

///

/// ftp文件上传、下载操作类

///

public class FTPHelper

{

///

/// ftp用户名,匿名为“”

///

private string ftpUser;

///

/// ftp用户密码,匿名为“”

///

private string ftpPassWord;

///

///通过用户名,密码连接到FTP服务器

///

/// ftp用户名,匿名为“”

/// ftp登陆密码,匿名为“”

public FTPHelper(string ftpUser, string ftpPassWord)

{

this.ftpUser = ftpUser;

this.ftpPassWord = ftpPassWord;

}

///

/// 匿名访问

///

public FTPHelper()

{

this.ftpUser = "";

this.ftpPassWord = "";

}

///

/// 上传文件到Ftp服务器

///

/// 把上传的文件保存为ftp服务器文件的uri,如"ftp://192.168.1.104/capture-212.avi"

/// 要上传的本地的文件路径,如D:\capture-2.avi

public void UpLoadFile(string UpLoadUri, string upLoadFile)

{

Stream requestStream = null;

FileStream fileStream = null;

FtpWebResponse uploadResponse = null;

try

{

Uri uri = new Uri(UpLoadUri);

FtpWebRequest uploadRequest = (FtpWebRequest)WebRequest.Create(uri);

uploadRequest.Method = WebRequestMethods.Ftp.UploadFile;

uploadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);

requestStream = uploadRequest.GetRequestStream();

fileStream = File.Open(upLoadFile, FileMode.Open);

byte[] buffer = new byte[1024];

int bytesRead;

while (true)

{

bytesRead = fileStream.Read(buffer, 0, buffer.Length);

if (bytesRead == 0)

break;

requestStream.Write(buffer, 0, bytesRead);

}

requestStream.Close();

uploadResponse = (FtpWebResponse)uploadRequest.GetResponse();

}

catch (Exception ex)

{

throw new Exception("上传文件到ftp服务器出错,文件名:" + upLoadFile + "异常信息:" + ex.ToString());

}

finally

{

if (uploadResponse != null)

uploadResponse.Close();

if (fileStream != null)

fileStream.Close();

if (requestStream != null)

requestStream.Close();

}

}

///

/// 从ftp下载文件到本地服务器

///

/// 要下载的ftp文件路径,如ftp://192.168.1.104/capture-2.avi

/// 本地保存文件的路径,如(@"d:\capture-22.avi"

public void DownLoadFile(string downloadUrl, string saveFileUrl)

{

Stream responseStream = null;

FileStream fileStream = null;

StreamReader reader = null;

try

{

// string downloadUrl = "ftp://192.168.1.104/capture-2.avi";

FtpWebRequest downloadRequest = (FtpWebRequest)WebRequest.Create(downloadUrl);

downloadRequest.Method = WebRequestMethods.Ftp.DownloadFile;

//string ftpUser = "yoyo";

//string ftpPassWord = "123456";

downloadRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);

FtpWebResponse downloadResponse = (FtpWebResponse)downloadRequest.GetResponse();

responseStream = downloadResponse.GetResponseStream();

fileStream = File.Create(saveFileUrl);

byte[] buffer = new byte[1024];

int bytesRead;

while (true)

{

bytesRead = responseStream.Read(buffer, 0, buffer.Length);

if (bytesRead == 0)

break;

fileStream.Write(buffer, 0, bytesRead);

}

}

catch (Exception ex)

{

throw new Exception("从ftp服务器下载文件出错,文件名:" + downloadUrl + "异常信息:" + ex.ToString());

}

finally

{

if (reader != null)

{

reader.Close();

}

if (responseStream != null)

{

responseStream.Close();

}

if (fileStream != null)

{

fileStream.Close();

}

}

}

///

/// 从FTP下载文件到本地服务器,支持断点下载

///

/// ftp文件路径,如"ftp://localhost/test.txt"

/// 保存文件的路径,如C:\\test.txt

public void BreakPointDownLoadFile(string ftpUri, string saveFile)

{

System.IO.FileStream fs = null;

System.Net.FtpWebResponse ftpRes = null;

System.IO.Stream resStrm = null;

try

{

//下载文件的URI

Uri u = new Uri(ftpUri);

//设定下载文件的保存路径

string downFile = saveFile;

//FtpWebRequest的作成

System.Net.FtpWebRequest ftpReq = (System.Net.FtpWebRequest)

System.Net.WebRequest.Create(u);

//设定用户名和密码

ftpReq.Credentials = new System.Net.NetworkCredential(ftpUser, ftpPassWord);

//MethodにWebRequestMethods.Ftp.DownloadFile("RETR")设定

ftpReq.Method = System.Net.WebRequestMethods.Ftp.DownloadFile;

//要求终了后关闭连接

ftpReq.KeepAlive = false;

//使用ASCII方式传送

ftpReq.UseBinary = false;

//设定PASSIVE方式无效

ftpReq.UsePassive = false;

//判断是否继续下载

//继续写入下载文件的FileStream

if (System.IO.File.Exists(downFile))

{

//继续下载

ftpReq.ContentOffset = (new System.IO.FileInfo(downFile)).Length;

fs = new System.IO.FileStream(

downFile, System.IO.FileMode.Append, System.IO.FileAccess.Write);

}

else

{

//一般下载

fs = new System.IO.FileStream(

downFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);

}

//取得FtpWebResponse

ftpRes = (System.Net.FtpWebResponse)ftpReq.GetResponse();

//为了下载文件取得Stream

resStrm = ftpRes.GetResponseStream();

//写入下载的数据

byte[] buffer = new byte[1024];

while (true)

{

int readSize = resStrm.Read(buffer, 0, buffer.Length);

if (readSize == 0)

break;

fs.Write(buffer, 0, readSize);

}

}

catch (Exception ex)

{

throw new Exception("从ftp服务器下载文件出错,文件名:" + ftpUri + "异常信息:" + ex.ToString());

}

finally

{

fs.Close();

resStrm.Close();

ftpRes.Close();

}

}

#region 从FTP上下载整个文件夹,包括文件夹下的文件和文件夹

///

/// 列出FTP服务器上面当前目录的所有文件和目录

///

/// FTP目录

///

public List ListFilesAndDirectories(string ftpUri)

{

WebResponse webresp = null;

StreamReader ftpFileListReader = null;

FtpWebRequest ftpRequest = null;

try

{

ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri(ftpUri));

ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

ftpRequest.Credentials = new NetworkCredential(ftpUser, ftpPassWord);

webresp = ftpRequest.GetResponse();

ftpFileListReader = new StreamReader(webresp.GetResponseStream(), Encoding.Default);

}

catch (Exception ex)

{

throw new Exception("获取文件列表出错,错误信息如下:" + ex.ToString());

}

string Datastring = ftpFileListReader.ReadToEnd();

return GetList(Datastring);

}

///

/// 列出FTP目录下的所有文件

///

/// FTP目录

///

public List ListFiles(string ftpUri)

{

List listAll = ListFilesAndDirectories(ftpUri);

List listFile = new List();

foreach (FileStruct file in listAll)

{

if (!file.IsDirectory)

{

listFile.Add(file);

}

}

return listFile;

}

///

/// 列出FTP目录下的所有目录

///

/// FRTP目录

/// 目录列表

public List ListDirectories(string ftpUri)

{

List listAll = ListFilesAndDirectories(ftpUri);

List listDirectory = new List();

foreach (FileStruct file in listAll)

{

if (file.IsDirectory)

{

listDirectory.Add(file);

}

}

return listDirectory;

}

///

/// 获得文件和目录列表

///

/// FTP返回的列表字符信息

private List GetList(string datastring)

{

List myListArray = new List();

string[] dataRecords = datastring.Split('\n');

FileListStyle _directoryListStyle = GuessFileListStyle(dataRecords);

foreach (string s in dataRecords)

{

if (_directoryListStyle != FileListStyle.Unknown && s != "")

{

FileStruct f = new FileStruct();

f.Name = "..";

switch (_directoryListStyle)

{

case FileListStyle.UnixStyle:

f = ParseFileStructFromUnixStyleRecord(s);

break;

case FileListStyle.WindowsStyle:

f = ParseFileStructFromWindowsStyleRecord(s);

break;

}

if (!(f.Name == "." || f.Name == ".."))

{

myListArray.Add(f);

}

}

}

return myListArray;

}

///

/// 从Unix格式中返回文件信息

///

/// 文件信息

private FileStruct ParseFileStructFromUnixStyleRecord(string Record)

{

FileStruct f = new FileStruct();

string processstr = Record.Trim();

f.Flags = processstr.Substring(0, 10);

f.IsDirectory = (f.Flags[0] == 'd');

processstr = (processstr.Substring(11)).Trim();

_cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //跳过一部分

f.Owner = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);

f.Group = _cutSubstringFromStringWithTrim(ref processstr, ' ', 0);

_cutSubstringFromStringWithTrim(ref processstr, ' ', 0); //跳过一部分

string yearOrTime = processstr.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[2];

if (yearOrTime.IndexOf(":") >= 0) //time

{

processstr = processstr.Replace(yearOrTime, DateTime.Now.Year.ToString());

}

f.CreateTime = DateTime.Parse(_cutSubstringFromStringWithTrim(ref processstr, ' ', 8));

f.Name = processstr; //最后就是名称

return f;

}

///

/// 从Windows格式中返回文件信息

///

/// 文件信息

private FileStruct ParseFileStructFromWindowsStyleRecord(string Record)

{

FileStruct f = new FileStruct();

string processstr = Record.Trim();

string dateStr = processstr.Substring(0, 8);

processstr = (processstr.Substring(8, processstr.Length - 8)).Trim();

string timeStr = processstr.Substring(0, 7);

processstr = (processstr.Substring(7, processstr.Length - 7)).Trim();

DateTimeFormatInfo myDTFI = new CultureInfo("en-US", false).DateTimeFormat;

myDTFI.ShortTimePattern = "t";

f.CreateTime = DateTime.Parse(dateStr + " " + timeStr, myDTFI);

if (processstr.Substring(0, 5) == "

{

f.IsDirectory = true;

processstr = (processstr.Substring(5, processstr.Length - 5)).Trim();

}

else

{

string[] strs = processstr.Split(new char[] { ' ' },2);// StringSplitOptions.RemoveEmptyEntries); // true);

processstr = strs[1];

f.IsDirectory = false;

}

f.Name = processstr;

return f;

}

///

/// 按照一定的规则进行字符串截取

///

/// 截取的字符串

/// 查找的字符

/// 查找的位置

private string _cutSubstringFromStringWithTrim(ref string s, char c, int startIndex)

{

int pos1 = s.IndexOf(c, startIndex);

string retString = s.Substring(0, pos1);

s = (s.Substring(pos1)).Trim();

return retString;

}

///

/// 判断文件列表的方式Window方式还是Unix方式

///

/// 文件信息列表

private FileListStyle GuessFileListStyle(string[] recordList)

{

foreach (string s in recordList)

{

if (s.Length > 10

&& Regex.IsMatch(s.Substring(0, 10), "(-|d)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)(-|r)(-|w)(-|x)"))

{

return FileListStyle.UnixStyle;

}

else if (s.Length > 8

&& Regex.IsMatch(s.Substring(0, 8), "[0-9][0-9]-[0-9][0-9]-[0-9][0-9]"))

{

return FileListStyle.WindowsStyle;

}

}

return FileListStyle.Unknown;

}

///

/// 从FTP下载整个文件夹

///

/// FTP文件夹路径

/// 保存的本地文件夹路径

public void DownFtpDir(string ftpDir, string saveDir)

{

List files = ListFilesAndDirectories(ftpDir);

if (!Directory.Exists(saveDir))

{

Directory.CreateDirectory(saveDir);

}

foreach (FileStruct f in files)

{

if (f.IsDirectory) //文件夹,递归查询

{

DownFtpDir(ftpDir + "/" + f.Name, saveDir + "\\" + f.Name);

}

else //文件,直接下载

{

DownLoadFile(ftpDir + "/" + f.Name, saveDir + "\\" + f.Name);

}

}

}

#endregion

}

#region 文件信息结构

public struct FileStruct

{

public string Flags;

public string Owner;

public string Group;

public bool IsDirectory;

public DateTime CreateTime;

public string Name;

}

public enum FileListStyle

{

UnixStyle,

WindowsStyle,

Unknown

}

#endregion

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值