今天做了通过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 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 = listMapFtp.showList("192.168.50.23", 21,
"admin", "123456", remotePath);// 获得ftp对应路径下的所有目录和文件信息
List listDirectory = list.get(0);// 获得ftp该路径下的所有目录信息
List listFile = list.get(1);// 获得ftp该路径下所有的文件信息
Map modelMap = new HashMap();
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> showList(String hostname, int port,
String username, String password, String pathname)
throws IOException {
FTPClient ftpClient = new FTPClient();
List listFile = new ArrayList();
List listDirectory = new ArrayList();
List> listMap = new ArrayList>();
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"%>
Insert title here
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[i].name+"
");
}
for(var i = 0;i "+listFile[i].name+"
");
}
}
});
}
7、登陆页面显示效果如下:
出处:http://blog.csdn.net/cl05300629/article/details/10110991 作者:伫望碧落