今天做了通过ftp读取ftp根目录下的所有文件夹和文件,嵌套文件夹查询,总共用到了一下代码:

1、FtpFile_Directory

package com.hs.dts.web.ftp;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "ftp")
public class FtpFile_Directory {

private Logger logger = LogManager.getLogger(FtpFile_Directory.class);

@Autowired
private ListMapFtp listMapFtp;
@Autowired
private DownloadFtp downloadFtp;

@RequestMapping(value = "showList")
@ResponseBody
public Map<String, Object> showList(HttpServletRequest request,
HttpServletResponse response) throws IOException {
HttpSession session = request.getSession();
String remotePath = request.getParameter("remotePath");// 获得当前路径
if (remotePath != null) {
logger.debug("remotePath--->" + remotePath);
session.setAttribute("sessionPath", remotePath);// 将当前路径保存到session中
}
if (remotePath == null) {
remotePath = "";
}
String filename = request.getParameter("filename");// 获得当前文件的名称
if (filename != null) {
logger.debug("filename:---> " + filename);
}
List<List<DtsFtpFile>> list = listMapFtp.showList("192.168.50.23", 21,
"admin", "123456", remotePath);// 获得ftp对应路径下的所有目录和文件信息
List<DtsFtpFile> listDirectory = list.get(0);// 获得ftp该路径下的所有目录信息
List<DtsFtpFile> listFile = list.get(1);// 获得ftp该路径下所有的文件信息

Map<String, Object> modelMap = new HashMap<String, Object>();
if (remotePath != null && filename == null) {// 如果前台点击的是目录则显示该目录下的所有目录和文件
modelMap.put("listDirectory", listDirectory);
modelMap.put("listFile", listFile);
} else if (filename != null) {// 如果前台点击的是文件,则下载该文件
String sessionPath = (String) session.getAttribute("sessionPath");// 获得保存在session中的当前路径信息
downloadFtp.downFile("192.168.50.23", 21, "admin", "123456",
sessionPath, filename, "D:/test/download/");
}
return modelMap;
}

@RequestMapping(value = "directJsp")
public String directJsp() {
logger.debug("--->into ftp/ftp-list.jsp");
return "ftp/ftp-list";
}
}

2、ListMapFtp

package com.hs.dts.web.ftp;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component("listMapFtp")
@Transactional
public class ListMapFtp {

private Logger logger = LogManager.getLogger(FtpFile_Directory.class);

public List<List<DtsFtpFile>> showList(String hostname, int port,
String username, String password, String pathname)
throws IOException {
FTPClient ftpClient = new FTPClient();
List<DtsFtpFile> listFile = new ArrayList<DtsFtpFile>();
List<DtsFtpFile> listDirectory = new ArrayList<DtsFtpFile>();
List<List<DtsFtpFile>> listMap = new ArrayList<List<DtsFtpFile>>();

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
int reply;
// 创建ftp连接
ftpClient.connect(hostname, port);
// 登陆ftp
ftpClient.login(username, password);
// 获得ftp反馈,判断连接状态
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
}
// 切换到指定的目录
ftpClient.changeWorkingDirectory(pathname + "/");

// 获得指定目录下的文件夹和文件信息
FTPFile[] ftpFiles = ftpClient.listFiles();

for (FTPFile ftpFile : ftpFiles) {
DtsFtpFile dtsFtpFile = new DtsFtpFile();
// 获取ftp文件的名称
dtsFtpFile.setName(ftpFile.getName());
// 获取ftp文件的大小
dtsFtpFile.setSize(ftpFile.getSize());
// 获取ftp文件的最后修改时间
dtsFtpFile.setLastedUpdateTime(formatter.format(ftpFile
.getTimestamp().getTime()));
if (ftpFile.getType() == 1 && !ftpFile.getName().equals(".")
&& !ftpFile.getName().equals("..")) {
// mapDirectory.put(ftpFile.getName(),
// pathname+"/"+ftpFile.getName());
// 获取ftp文件的当前路劲
dtsFtpFile.setLocalPath(pathname + "/" + ftpFile.getName());
listDirectory.add(dtsFtpFile);
} else if (ftpFile.getType() == 0) {
// mapFile.put(ftpFile.getName(),ftpFile.getName());
dtsFtpFile.setLocalPath(pathname + "/");
listFile.add(dtsFtpFile);
}
// System.out.println("Name--->"+ftpFile.getName()+"\tTimestamp--->"+ftpFile.getTimestamp().getTime()+"\tsize--->"+ftpFile.getSize());
// double fileSize = (double) ftpFile.getSize();
// if(fileSize/(1024*1024*1024)>1){
// System.out.println(ftpFile.getName()+" size is "+df.format(fileSize/(1024*1024*1024))+"GB");
// }else if(fileSize/(1024*1024)>1){
// System.out.println(ftpFile.getName()+" size is "+df.format(fileSize/(1024*1024))+"MB");
// }else if(fileSize/1024>1){
// System.out.println(ftpFile.getName()+" size is "+df.format(fileSize/1024)+"KB");
// }else if(fileSize/1024<1){
// System.out.println(ftpFile.getName()+" size is "+ftpFile.getSize()+"B");
// }
}
listMap.add(listDirectory);
listMap.add(listFile);
ftpClient.logout();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
return listMap;
}
}

3、DownloadFtp

package com.hs.dts.web.ftp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component("downloadFtp")
@Transactional
public class DownloadFtp {

/**
* Description:从ftp服务器下载文件 version1.0

* @param url
*            FTP服务器hostname
* @param port
*            FTP服务器端口
* @param username
*            FTP登陆账号
* @param password
*            FTP登陆密码
* @param path
*            FTP服务器上的相对路径
* @param filename
*            要下载的文件名
* @return 成功返回true,否则返回false
*/
public boolean downFile(String url,// FTP服务器hostname
int port,// FTP服务器端口
String username,// FTP登陆账号
String password,// FTP登陆密码
String remotePath,// FTP服务器上的相对路径
String fileName,// 要下载的文件名
String localPath// 下载后保存到本地的路劲
) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);
// 如果采用端口默认,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);// 登陆
//System.out.println("login!");
reply = ftp.getReplyCode();
//System.out.println("reply:" + reply);
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.changeWorkingDirectory(remotePath+"/");// 转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
// System.out.println("名称:"+ff.getName()+"类型:"+ff.getType());
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + '/' + ff.getName());
OutputStream os = new FileOutputStream(localFile);
ftp.retrieveFile(ff.getName(), os);
os.close();
}
}
System.out.println("upload success!");
ftp.logout();
//System.out.println("logout!");
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
return success;
}
}

4、DtsFtpFile

package com.hs.dts.web.ftp;

public class DtsFtpFile {
private String name;
private long size;
private String lastedUpdateTime;
private String localPath;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
public String getLastedUpdateTime() {
return lastedUpdateTime;
}
public void setLastedUpdateTime(String lastedUpdateTime) {
this.lastedUpdateTime = lastedUpdateTime;
}
public String getLocalPath() {
return localPath;
}
public void setLocalPath(String localPath) {
this.localPath = localPath;
}
}

5、jsp页面

<%@ page contentType="text/html;charset=UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"/>
<title>Insert title here</title>
<script type="text/javascript" src="${ctx}/static/jquery/1.7.2/jquery.js"></script>
<script type="text/javascript">
var ctx = '${ctx}';
}
</script>
 <script type="text/javascript" src="${ctx}/static/js/ftp/ftp.js">
</script>
<style type="text/css">
 a:link {
    text-decoration:none;
    }
    a:hover {
    text-decoration:underline;
    }
</style>
</head>
<body>
    <div id="rootDirectory">
    <a onclick='showList(this.id)' href='#' style='color:red;' id='${ctx}/ftp/showList?remotePath='>根目录</a><br/><br/>
    </div>
    <div id="container"></div>
</body>
</html>

6、脚本文件

Ext.onReady(function(){
showList(ctx+'/ftp/showList');
});
function showList(url){
Ext.Ajax.request({
        url : url,
        method:'post',
        async:false,  
        success : function(response) {
        var listDirectory = Ext.util.JSON.decode(response.responseText).listDirectory;
        var listFile = Ext.util.JSON.decode(response.responseText).listFile;
        $("#container").empty();
        for(var i = 0;i<listDirectory.length;i++){
        $("#container").append("<img src="+ctx+"/static/images/ftp/directory.jpg width='25px' height='25px'>&nbsp<a onclick='showList(this.id)' href='#' style='color:blue' name ='"+listDirectory[i].localPath+" 'id='"+ctx+"/ftp/showList?remotePath="+listDirectory[i].localPath+"'>"+listDirectory[i].name+"</a><br/>");
        }
        for(var i = 0;i<listFile.length;i++){
        $("#container").append("<img src="+ctx+"/static/images/ftp/file.jpg width='25px' height='25px'>&nbsp<a onclick='showList(this.id)' href='#' style='color:green' id='"+ctx+"/ftp/showList?filename="+listFile[i].name+"'>"+listFile[i].name+"</a><br/>");
        }
        }
    });
}

7、登陆页面显示效果如下:

出处:http://blog.csdn.net/cl05300629/article/details/10110991 作者:伫望碧落

遍历、显示ftp下的文件夹和文件信息的更多相关文章

  1. 通过ftp同步服务器文件:遍历文件夹所有文件(含子文件夹、进度条);简单http同步服务器文件实例

    该代码主要实现,指定ftp服务地址,遍历下载该地址下所有文件(含子文件夹下文件),并提供进度条显示:另外附带有通过http地址方式获取服务器文件的简单实例 废话不多说,直接上代码: 1.FTPHelp ...

  2. PHP遍历目录下的文件夹和文件 以及遍历文件下内容

    1.遍历目录下的文件夹和文件: public function bianli1($dir) { $files = array(); if($head = opendir($dir)) { while( ...

  3. 递归遍历磁盘下的某一文件夹中所有文件,并copy文件生成文件和带文件夹的文件

    package com.hudong.test; import java.io.File; import java.io.IOException; import java.util.ArrayList ...

  4. VBA读取文件夹下所有文件夹及文件内容,并以树形结构展示

    Const TR_LEVEL_MARK = "+"Const TR_COL_INDEX = "A"Const TR_COL_LEVEL = "E&qu ...

  5. scp 对拷文件夹 和 文件夹下的所有文件 对拷文件并重命名

    对拷文件夹 (包括文件夹本身) scp -r   /home/wwwroot/www/charts/util root@192.168.1.65:/home/wwwroot/limesurvey_ba ...

  6. C/C++遍历文件夹和文件

    本方法可用于windows和linux双平台,采用C/C++标准库函数. 库函数 包含头文件 #include 用到数据结构_finddata_t,文件信息结构体的指针. struct _findda ...

  7. TortoiseSVN文件夹及文件图标不显示解决方法

              由于自己的电脑是win7(64位)的,系统安装TortoiseSVN之后,其他的功能都能正常的使用,但是就是文件夹或文件夹的左下角就是不显示图标,这个问题前一段时间就遇到了(那个时 ...

  8. python 实现彻底删除文件夹和文件夹下的文件

    python 中有很多内置库可以帮忙用来删除文件夹和文件,当面对要删除多个非空文件夹,并且目录层次大于3层以上时,仅使用一种内置方法是无法达到彻底删除文件夹和文件的效果的,比较low的方式是多次调用直 ...

  9. [转]TortoiseSVN文件夹及文件图标不显示解决方法

    FROM : http://blog.csdn.net/lishehe/article/details/8257545 由于自己的电脑是win7(64位)的,系统安装TortoiseSVN之后,其他的 ...

随机推荐

  1. Android 自定义View修炼-Android开发之自定义View开发及实例详解

    在开发Android应用的过程中,难免需要自定义View,其实自定义View不难,只要了解原理,实现起来就没有那么难. 其主要原理就是继承View,重写构造方法.onDraw,(onMeasure)等 ...

  2. MFC/VC++ 响应回车键的实现

    在VC++中,要实现对回车键的响应实现,一般通过截获消息来响应,即通过处理BOOL PreTranslateMessage(MSG* pMsg)这个函数来处理 实现如下: BOOL PreTransl ...

  3. Papers

    Research on Semantic Text Mining Based on Domain Ontologyhttp://link.springer.com/chapter/10.1007/97 ...

  4. Android Studio SDK Manager无法正常下载如何设置

    博客分类: Linux 零散小知识 Android那点事 AndroidStudioSDKManager  一方面在/etc/hosts中设置: #Google主页 203.208.46.146 ww ...

  5. 组策略彻底解决windows 2003 终端数

         win2003的话可以从组策略修改: 组策略级别要高于终端服务配置,当启用组策略后终端服务配置中的相应选项会变成灰色不可修改 运行-gpedit.msc-计算机配置-管理模板-Windows ...

  6. 检查.gitignore语法

    每次配置git的时候,要写gitignore文件,你知道你的.gitignore匹配那些文件吗? 看看.gitignore放过了哪些文件: git ls-files -ocm --exclude-st ...

  7. 菜鸟日记之 java中的集合框架

    java中的集合框架图 如图所示:java中的集合分为两种Collection和Map两种接口 可分为Collection是单列集合和Map的双列集合 Collection单列集合:继承了Iterat ...

  8. deep learning 学习资料

    http://deeplearning.net/tutorial/lenet.html

  9. python细节

    1.assert 断言语句,可判断一句话真假,若为假会抛出AssertionError. eg. assert 1==1     assert 1==2则AssertionError 2.单引号双引号 ...

  10. 如何更有效学习php开源项目的源码

    一.先把源代码安装起来,结合它的文档和手册,熟悉其功能和它的应用方式. 二.浏览源代码的目录结构,了解各个目录的功能. 三.经过以上两步后相信你对这个开源的产品有了一个初步的了解了,那现在就开始分析它 ...