hadoop与java简单交互

首先要在linux上搭建hadoop环境,具体的实现步骤在http://phey.cc/build_signal_node_hadoop20.html

搭建好之后,在Eclipse 或Myeclipse上与hadoop交互,我用的是hadoop2.3,文章会给出附件,解压出hadoop2.3,下载Eclipse 或Myeclipse的hadoop插件,我用的是hadoop-eclipse-plugin-2.2.0.jar,把这个插件放在Myeclipse的dropins和plugins文件夹下,打开Myeclipse,window-open perspective-other,找到,Map/Reduce选项,如果没有,请检查一下dropins和plugins文件夹是否有hadoop-eclipse-plugin-2.2.0.jar这个文件,还有一个原因就是IDE版本太低,换一个高点的版本。打开Map/Reduce后会有那么一个标志,说明安装成功了,然后打开Map/Reduce的视图 window-show view-other-MapReduce Tools,打开后点击添加图标,

location name: 这个随便填写

 

map/reduce master 这个框里

host:就是jobtracker 所在的集群机器,笔者这里是单机伪分布式,jobtracker就在这个机器上,所以填上这个机器的ip

port:就是jobtracker 的port,这里写的是9001

 

这两个参数就是 mapred-site.xml里面mapred.job.tracker里面的ip和port

 

 

DFS master这个框里

host:就是namenode所在的集群机器,笔者这里是单机伪分布式,namenode就在这个机器上,所以填上这个机器的ip。

port:就是namenode的port,这里写9000

 

这两个参数就是 core-site.xml里fs.default.name里面的ip和port(use M\R master host,这个复选框如果选上,就默认和map\reduce master 这个框里的 host一样,如果不选择,就可以自己定义输入,这里jobtracker 和namenode在一个机器上,所以是一样的,就勾选上)

 

 

username:这个是连接hadoop的用户名,因为笔者是在linux中用root用户安装的hadoop,而且没建立其他的用户,所以就用root。然后点击 finish按钮,此时,这个视图中就有多了一条记录。有很多文章要编辑tab页,那么也说一下tab页的内容吧。重启Myeclipse,

fs.defualt.name:这个在General tab页已经设置了。

mapred.job.tracker:这个在General tab页也设置了。

 

dfs.replication:这个这里默认是3,因为我们再hdfs-site.xml里面设置成了1,所以这里也要设置成1

hadoop.tmp.dir:这个默认是/tmp/hadoop-{user.name},因为我们在ore-defaulte.xml 里hadoop.tmp.dir设置的是/usr/local/hadoop/hadooptmp,所以这里我们也改成/usr/local/hadoop/hadooptmp,其他基于这个目录属性也会自动改

 

hadoop.job.ugi:刚才说看不见的那个,就是这个属性,这里要填写:root,Tardis,逗号前面的是连接的hadoop的用户,逗号后面就写死Tardis。


hadoop.job.ugi如果没有,可以不用管。至此就可以看到hadoop的文件系统了。




下面我们编写读取 hadoop上文件的java类,我做的是这样一个东西:在html页面上显示出hadoop系统上的文件,点击文件可进行下载,点击文件夹进入子文件,点击预览,可对预览文件的大致内容。例如:给出一个路径,读取该路径的所有文件、文件夹,及其子文件和子文件夹,并用ztree控件展示目录树,java据说有红黑树那么一个东西,本人菜鸟,没有对那个进行研究,于是自己写了这个一个类。

Treenode类

import java.util.List;

public class TreeNode {

	private String name;  //路径名
	private List<TreeNode> children; //子路径
	private String path;//文件的地址  

	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<TreeNode> getChildren() {
		return children;
	}

	public void setChildren(List<TreeNode> children) {
		this.children = children;
	}

}

再来看看Controller  

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URI;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.Progressable;
import org.apache.log4j.Logger;
import org.athena.basic.model.Test;
import org.athena.basic.service.TestService;
import org.athena.util.File;
import org.athena.util.PreviewFiles;
import org.athena.util.TreeNode;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Component
@RequestMapping(value = "/")
// 测试Controller
public class TestController {
    private static Logger logger = Logger.getLogger(Test.class);
    private static List<TreeNode> nodes = new ArrayList<TreeNode>();  
    private static Configuration config = new Configuration();
    private TestService testService;
    private TreeNode cNode=new TreeNode();
<span style="white-space:pre">	</span>
    @RequestMapping(value = "showFile")
    public String showFile(HttpServletRequest request, ModelMap modelMap)
        throws IOException {
        String cpath = request.getParameter("cpath");
        FileSystem fs = FileSystem.get(config);
        nodes.clear();

        Test test = testService.findTestByUUID(request.getParameter("path"));
        TreeNode node = new TreeNode();
        String Path1st = null;
        String Path2nd = null;
        String Path3rd = null;
        String Path4th = null;
        
        if (cpath == null) {
            Path1st = request.getParameter("path").toString().substring(0, 4);
            Path2nd = request.getParameter("path").toString().substring(5, 9);
            Path3rd = request.getParameter("path").toString().substring(10, 14);
            Path4th = request.getParameter("path").toString().substring(15,request.getParameter("path").toString().length());
            String  path = "hdfs://192.168.0.187:8020/home/cc/file/" + Path1st +"/" + Path2nd + "/" + Path3rd + "/" + Path4th;
            node.setName(test.getIp());
            node.setPath(path);
            /*
             * 只读取出本IP的目录树
             */
            if (fs.exists(new Path(path))) {
            	cNode.setPath(path);
                nodes=new TestController().printMenu(path, cNode);
            }
            TreeNode node2=new TreeNode();
            node2.setName(Path1st);
            
            TreeNode node3=new TreeNode();
            node3.setName(Path2nd);
            
            
            TreeNode node4=new TreeNode();
            node4.setName(Path3rd);
            
            List<TreeNode> list4=new ArrayList<TreeNode>();
            list4.add(nodes.get(nodes.size()-1));
            node4.setChildren(list4);
            

            List<TreeNode> list3=new ArrayList<TreeNode>();
            list3.add(node4);
            node3.setChildren(list3);
            
            
            List<TreeNode> list2=new ArrayList<TreeNode>();
            list2.add(node3);
            node2.setChildren(list2);
            List<TreeNode> list1=new ArrayList<TreeNode>();
            list1.add(node2);
            node.setChildren(list1);
        }
        request.getSession().setAttribute("treestr", JSONArray.fromObject(node).toString().replaceAll("\"", "'"));
        request.getSession().setAttribute("path",Path1st + "/" + Path2nd + "/" + Path3rd + "/" + Path4th);
        request.getSession().setAttribute("descr", test.getDescr());
        return "/files.html";
    }

    @RequestMapping(value = "showAll")
    public ModelAndView showAll(HttpServletRequest request,
        HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");

        String path = request.getParameter("path");
        if ((path != null) && !path.toString().trim().equals("")) {
            Configuration conf = new Configuration();
            FileSystem hdfs = FileSystem.get(conf);
            Path fpath = new Path(path);

            if (hdfs.exists(fpath)) {
                FileStatus[] status = hdfs.listStatus(fpath);
                List<File> files = new ArrayList<File>();

                for (int i = 0; i < status.length; i++) {
                    String icon = null;

                    if (status[i].getPath().getName().toString().lastIndexOf(".") != -1) {
                        icon = status[i].getPath().getName()
                                        .substring(status[i].getPath().getName()
                                                            .toString()
                                                            .lastIndexOf(".") +
                                1,
                                status[i].getPath().getName().toString().length());
                    } else {
                        icon = null;
                    }

                    File file = new File(status[i].getPath().toString(),
                            convertFileSize(status[i].getLen()),
                            String.valueOf(
                                new Timestamp(status[i].getModificationTime())),
                            status[i].getOwner(),
                            String.valueOf(status[i].getReplication()),
                            String.valueOf(status[i].getBlockSize()),
                            status[i].getGroup(),
                            status[i].getPermission().toString(),
                            status[i].getPath().getName(), getIcon(icon));
                    files.add(file);
                }

                response.reset();
                response.setContentType("text/Xml;charset=UTF-8");

                PrintWriter out = null;

                try {
                    out = response.getWriter();
                    out.println(JSONArray.fromObject(files).toString().replaceAll("\"", "'"));
                } catch (IOException ex1) {
                    ex1.printStackTrace();
                } finally {
                    out.flush();
                    out.close();
                    hdfs.close();
                }
            }
        }

        return null;
    }
  
    @RequestMapping(value = "previewFile")
    public ModelAndView previewFile(HttpServletRequest request,
        ModelMap modelMap, HttpServletResponse response)
        throws IOException {
        PrintWriter out = null;
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");
        out = response.getWriter();

        try {
            String pathString = request.getParameter("path");
            FileSystem hdfs = FileSystem.get(config);
            Path path = new Path(pathString);

            if (hdfs.isFile(path)) {
                String suffix = path.getName().toString().substring(path.getName().toString().lastIndexOf(".") + 1,path.getName().toString().length());
                if (suffix.equals("doc")) {
                    out.println(PreviewFiles.previewWord(pathString, request));
                } else if (suffix.equals("ppt")) {
                    out.println(PreviewFiles.previewPPT(pathString));
                } else if (suffix.equals("pdf")) {
                    out.println(PreviewFiles.previewPdf(pathString));
                } else if (suffix.equals("xls")) {
                    out.println(PreviewFiles.previewExcel(pathString));
                } else if (suffix.equals("txt") || suffix.equals("ini") ||suffix.equals("cnf")) {
                    out.println(PreviewFiles.previewTxt(pathString));
                } else if (suffix.equals("gif") || suffix.equals("jpg") ||suffix.equals("jpeg") || suffix.equals("png")) {
                    response.reset();
                    FSDataInputStream fin = hdfs.open(new Path(pathString));
                    int i = fin.available(); // 得到文件大小
                    byte[] data = new byte[i];
                    fin.read(data); // 读数据
                    
                    OutputStream toClient = response.getOutputStream(); // 得到向客户端输出二进制数据的对象
                    toClient.write(data); // 输出数据
                    toClient.flush();
                    toClient.close();
                    fin.close();
                } else if (suffix.equals("xml")) {
                    out.println(PreviewFiles.previewXml(pathString));
                } else {
                    out.println("没有预览");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e);
        }

        out.flush();
        out.close();

        return null;
    }
    //前台传值 文件路径  文件路径是 hadoop系统的文件路径  
   //显示该文件夹下的内容
    @RequestMapping(value = "showChildren")
    public ModelAndView showChildren(HttpServletRequest request,
        ModelMap modelMap, HttpServletResponse response)
        throws IOException {
        response.setCharacterEncoding("UTF-8");
        request.setCharacterEncoding("UTF-8");

        String path = request.getParameter("path");
        Configuration conf = new Configuration();
        FileSystem hdfs = FileSystem.get(conf);
        Path fpath = new Path(path);

        try {
            if (hdfs.exists(fpath)) {
                if (hdfs.isDirectory(fpath)) {
                    FileStatus[] status = hdfs.listStatus(fpath);
                    List<File> files = new ArrayList<File>();

                    for (int i = 0; i < status.length; i++) {
                        String icon = null;

                        if (status[i].getPath().getName().toString()
                                         .lastIndexOf(".") != -1) {
                            icon = status[i].getPath().getName()
                                            .substring(status[i].getPath()
                                                                .getName()
                                                                .toString()
                                                                .lastIndexOf(".") +
                                    1,
                                    status[i].getPath().getName().toString()
                                             .length());
                        } else {
                            icon = null;
                        }

                        File file = new File(status[i].getPath().toString(),
                                convertFileSize(status[i].getLen()),
                                String.valueOf(
                                    new Timestamp(
                                        status[i].getModificationTime())),
                                status[i].getOwner(),
                                String.valueOf(status[i].getReplication()),
                                String.valueOf(status[i].getBlockSize()),
                                status[i].getGroup(),
                                status[i].getPermission().toString(),
                                status[i].getPath().getName(), getIcon(icon));
                        files.add(file);
                    }

                    String jsonsString = JSONArray.fromObject(files).toString();
                    response.setCharacterEncoding("utf-8");
                    response.getWriter().write(jsonsString);
                    response.getWriter().flush();
                } else {
                    doDownload(request, path, response);

                    return null;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
<span style="white-space:pre">	</span>//调用浏览器的下载功能,同样穿的值是  hadoop的文件路径
    public void doDownload(HttpServletRequest request, String path,
        HttpServletResponse response) throws IOException {
        if (path != null) {
            Path path2 = new Path(path);
            FileSystem fs = FileSystem.get(URI.create(path2.toString()), config); // 构建FileSystem

            if (fs.exists(path2)) {
                FSDataInputStream HDFS_IN = fs.open(new Path(path2.toString()));
                InputStream is = fs.open(new Path(path2.toString())); // 读取文件

                response.addHeader("Content-Disposition",
                    "attachment;filename=" +
                    new String(path2.getName().getBytes("utf-8"), "ISO8859-1"));
                response.addHeader("Content-Length", "" + HDFS_IN.available());

                ServletOutputStream outputStream = response.getOutputStream();
                response.setContentType("application/x-download");
                IOUtils.copyBytes(is, outputStream, 2048, true); // 保存到本地 最后 关闭
                outputStream.flush();
                outputStream.close();
                HDFS_IN.close();
            } else {
                Writer writer = response.getWriter();
                writer.write("<h3>File Not Found !<h3>");
                writer.flush();
                writer.close();
            }
        } else {
            try {
                response.sendRedirect("index.do");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String getIcon(String suffix) {
        String icon = null;
        if (suffix != null) {
            if (suffix.toLowerCase().equals("avi")) {
                icon = "avi.png";
            } else if (suffix.toLowerCase().equals("bmp")) {
                icon = "bmp.png";
            } else if (suffix.toLowerCase().equals("css")) {
                icon = "css.png";
            } else if (suffix.toLowerCase().equals("eml")) {
                icon = "eml.png";
            } else if (suffix.toLowerCase().equals("eps")) {
                icon = "eps.png";
            } else if (suffix.toLowerCase().equals("doc") ||suffix.toLowerCase().equals("docx")) {
                icon = "docx.png";
            } else if (suffix.toLowerCase().equals("ind")) {
                icon = "ind.png";
            } else if (suffix.toLowerCase().equals("gif")) {
                icon = "gif.png";
            } else if (suffix.toLowerCase().equals("html") ||suffix.toLowerCase().equals("htm")) {
                icon = "html.png";
            } else if (suffix.toLowerCase().equals("jpg") ||
                    suffix.toLowerCase().equals("jpeg")) {
                icon = "jpg.png";
            } else if (suffix.toLowerCase().equals("mdb")) {
                icon = "mdb.png";
            } else if (suffix.toLowerCase().equals("midi")) {
                icon = "midi.png";
            } else if (suffix.toLowerCase().equals("mp4")) {
                icon = "mp4.png";
            } else if (suffix.toLowerCase().equals("ppt") ||suffix.toLowerCase().equals("pptx")) {
                icon = "pptx.png";
            } else if (suffix.toLowerCase().equals("pdf")) {
                icon = "pdf.png";
            } else if (suffix.toLowerCase().equals("psd")) {
                icon = "psd.png";
            } else if (suffix.toLowerCase().equals("ini")) {
                icon = "ini.png";
            } else if (suffix.toLowerCase().equals("txt")) {
                icon = "txt.png";
            } else if (suffix.toLowerCase().equals("zip") ||suffix.toLowerCase().equals("rar") ||suffix.toLowerCase().equals("7z")) {
                icon = "rar.png";
            } else if (suffix.toLowerCase().equals("xls") ||suffix.toLowerCase().equals("xlsx")) {
                icon = "xlsx.png";
            } else if (suffix.toLowerCase().equals("png")) {
                icon = "png.png";
            } else {
                icon = "unknow.png";
            }
        } else {
            icon = "folder.png";
        }

        return icon;
    }

    private List<TreeNode> printMenu(String path, TreeNode nodep)
        throws IOException {
        List<TreeNode> cTreeNodes = new ArrayList<TreeNode>();
        FileStatus[] tu = FileSystem.get(config).listStatus(new Path(path));
        nodep.setName(path.substring(path.lastIndexOf("/") + 1, path.length()));
//        System.out.println(path);
        if (tu != null) {
            for (int q = 0; q < tu.length; q++) {
	            	if (FileSystem.get(config).isDirectory(tu[q].getPath())) {
	                    TreeNode node = new TreeNode();
	                    node.setPath(tu[q].getPath().toString());
	                    node.setName(tu[q].getPath().getName());
	                    cTreeNodes.add(node);
	                    printMenu(tu[q].getPath().toString(), node);
            	}
            }
            nodep.setChildren(cTreeNodes);
            nodes.add(nodep);
        }
               return nodes;
    }
    /**
     *
     * @param request
     * @param modelMap
     * @return
     * @throws IOException
     *             这个方法是4个路径的UUID
     */
    @RequestMapping(value = "updatauuid")
    public String doUpdate(HttpServletRequest request, ModelMap modelMap)
        throws IOException {
        List<Test> tests = testService.findAll();

        for (int i = 0; i < tests.size(); i++) {
            String Path1st = tests.get(i).getId().toString().substring(0, 4);
            String Path2nd = tests.get(i).getId().toString().substring(4, 8);
            String Path3rd = tests.get(i).getId().toString().substring(8, 12);
            String Path4th = tests.get(i).getId().toString().substring(12,tests.get(i).getId().toString().length());
            String path = Path1st + "-" + Path2nd + "-" + Path3rd + "-" +Path4th;
            String createPath = Path1st + "/" + Path2nd + "/" + Path3rd + "/" +Path4th;
            FileSystem fileSystem = FileSystem.get(config);
            fileSystem.mkdirs(new Path("hdfs://192.168.0.187:8020/home/cc/file/" + createPath));
            tests.get(i).setUuid(path);
            tests.get(i).setDescr("这台机器的UUID是:" + path);
            testService.updateTest(tests.get(i));
        }

        return "/test.html";
    }

    /**
     *
     * @param LOCAL_SRC
     *            本地文件路径
     * @param CLOUD_DEST
     *            上传的文件路径
     */
    @SuppressWarnings("unused")
    private void Upload(String LOCAL_SRC, String CLOUD_DEST) {
        InputStream in;
        OutputStream out;

        try {
            in = new BufferedInputStream(new FileInputStream(LOCAL_SRC));

            Configuration conf = new Configuration();
            FileSystem fs;
            fs = FileSystem.get(URI.create(CLOUD_DEST), conf);
            out = fs.create(new Path(CLOUD_DEST),
                    new Progressable() {
                        public void progress() {
                            System.out.println("上传完成一个文件到HDFS");
                        }
                    });
            IOUtils.copyBytes(in, out, 1024, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "test")
    public String doTest(HttpServletRequest request, ModelMap modelMap)
        throws Exception {
        List<Test> tests = testService.findAll();
        Configuration config = new Configuration();
        FileSystem fs = FileSystem.get(config);

        for (int i = 0; i < tests.size(); i++) {
            String Path1st = tests.get(i).getId().toString().substring(0, 4);
            String Path2nd = tests.get(i).getId().toString().substring(4, 8);
            String Path3rd = tests.get(i).getId().toString().substring(8, 12);
            String Path4th = tests.get(i).getId().toString().substring(12,tests.get(i).getId().toString().length());
            if (!fs.exists(new Path("hdfs://192.168.0.187:8020/home/cc/file/" +Path1st + "/" + Path2nd + "/" + Path3rd + "/" +Path4th))) {
                tests.get(i).setUuid("暂无文件");
            }
        }

        modelMap.put("tests", tests);

        return "/test.html";
    }
<span style="white-space:pre">	</span>
    public static String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;

        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;

            return String.format((f > 100) ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;

            return String.format((f > 100) ? "%.0f KB" : "%.1f KB", f);
        } else {
            return String.format("%d B", size);
        }
    }

    @Resource
    public void setTestService(TestService testService) {
        this.testService = testService;
    }

    public TestService getTestService() {
        return testService;
    }
}

html页面是这样实现的   test.html    这个页面只是传入一个值,也就是controller的参数。

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<title>Athena Test</title>
	<meta content="width=device-width, initial-scale=1.0" name="viewport" />
	<link rel="shortcut icon" href="${request.contextPath}/static/img/favicon.ico" type="image/x-icon">
	<link href="${request.contextPath}/assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
	<link href="${request.contextPath}/assets/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" />
	<link href="${request.contextPath}/assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
	<link href="${request.contextPath}/assets/css/style_responsive.css" rel="stylesheet" />
	<link href="${request.contextPath}/assets/css/metro.css" rel="stylesheet" />
	<link href="${request.contextPath}/assets/css/style.css" rel="stylesheet" />
	<link href="${request.contextPath}/assets/css/style_default.css" rel="stylesheet"/>
	<link rel="stylesheet" type="text/css" href="${request.contextPath}/assets/uniform/css/uniform.default.css" />
    <link rel="stylesheet" type="text/css" href="${request.contextPath}/gms/styles/admin.main.css" />
</head>
<body>
  <div class="content">
   <table class="table table-striped table-bordered"> 
	<tr><td>ID</td><td>名字</td><td>文件路径</td><td>操作</td></tr>	
	<#list tests as test>
    <tr><td>${test.id}</td><td>${test.name}</td><td>${test.uuid}</td>
    
    <td>
    <#if test.uuid!='暂无文件'>
    <a href="showFile.do?path=${test.uuid}">查看文件</a></td>
    <#else>
 		   暂无文件
    </#if>
    </tr> 
	</#list>
	</table>  
	<a href="updatauuid.do">修改</a>
  </div>
</body>
</html>

这个页面是主要内容    files.html 
<!DOCTYPE html>
<html>
 <head> 
 		<title>Athena Test</title> 
 		<meta charset="utf-8"/> 
 		<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
		<meta name="viewport" content="width=device-width">
		<link rel="shortcut icon" href="${request.contextPath}/static/img/favicon.ico" type="image/x-icon">
		<link href="${request.contextPath}/static/css/bootstrap.min.css" rel="stylesheet" media="screen" />
		<link href="${request.contextPath}/static/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen" />
		<link rel="stylesheet" href="${request.contextPath}/static/css/style.css" />
		<link rel="stylesheet" href="${request.contextPath}/plugin/jvectormap/jquery-jvectormap-1.2.2.css" />
		<script type="text/javascript" src="${request.contextPath}/script/jquery/jquery-1.8.3.min.js" ></script>
		<script type="text/javascript" src="${request.contextPath}/script/scroll/jquery-scroll-to-clk.js" ></script>
		<script type="text/javascript" src="${request.contextPath}/static/js/bootstrap.min.js" ></script>
	    <link rel="stylesheet" href="${request.contextPath}/plugin/ztree/css/demo.css" type="text/css" /> 
	    <link rel="stylesheet" href="${request.contextPath}/plugin/ztree/css/zTreeStyle/zTreeStyle.css" type="text/css" /> 
	    <script type="text/javascript" src="${request.contextPath}/plugin/ztree/js/jquery-1.4.4.min.js"></script> 
	    <script type="text/javascript" src="${request.contextPath}/plugin/ztree/js/jquery.ztree.core-3.5.js"></script> 
	    <script type="text/javascript" src="${request.contextPath}/plugin/ztree/js/jquery.ztree.excheck-3.5.js"></script> 
	    <script type="text/javascript" src="${request.contextPath}/plugin/ztree/js/jquery.ztree.exedit-3.5.js"></script> 
  		<script type="text/javascript">
		var setting = {
			check: {
				enable: true
			},
			data: {
				simpleData: {
					enable: true
				}
			},
			callback: {
				onNodeCreated: onNodeCreated,
				onClick: onClick
			}
		};

		var dataMaker = function(count) {
			json = eval("(" + $("#tree").val() + ")");
			var nodes =json;
			return nodes;
		}

		var ruler = {
			doc: null,
			ruler: null,
			cursor: null,
			minCount: 5000,
			count: 5000,
			stepCount:500,
			minWidth: 30,
			maxWidth: 215,
			init: function() {
				ruler.doc = $(document);
				ruler.ruler = $("#ruler");
				ruler.cursor = $("#cursor");
				if (ruler.ruler) {
					ruler.ruler.bind("mousedown", ruler.onMouseDown);
					
				}
			},
			onMouseDown: function(e) {
				ruler.drawRuler(e, true);
				ruler.doc.bind("mousemove", ruler.onMouseMove);
				ruler.doc.bind("mouseup", ruler.onMouseUp);
				ruler.doc.bind("selectstart", ruler.onSelect);
				$("body").css("cursor", "pointer");
			},
			onMouseMove: function(e) {
				ruler.drawRuler(e);
				return false;
			},
			onMouseUp: function(e) {
				$("body").css("cursor", "auto");
				ruler.doc.unbind("mousemove", ruler.onMouseMove);
				ruler.doc.unbind("mouseup", ruler.onMouseUp);
				ruler.doc.unbind("selectstart", ruler.onSelect);
				ruler.drawRuler(e);
			},
			onSelect: function (e) {
				return false;
			},
			getCount: function(end) {
				var start = ruler.ruler.offset().left+1;
				var c = Math.max((end - start), ruler.minWidth);
				c = Math.min(c, ruler.maxWidth);
				return {width:c, count:(c - ruler.minWidth)*ruler.stepCount + ruler.minCount};
			},
			drawRuler: function(e, animate) {
				var c = ruler.getCount(e.clientX);
				ruler.cursor.stop();
				if ($.browser.msie || !animate) {
					ruler.cursor.css({width:c.width});
				} else {
					ruler.cursor.animate({width:c.width}, {duration: "fast",easing: "swing", complete:null});
				}
				ruler.count = c.count;
				ruler.cursor.text(c.count);
			}
		}
		var showNodeCount = 0;
		function onNodeCreated(event, treeId, treeNode) {
			showNodeCount++;
		}
        function onClick(event, treeId, treeNode,clickFlag) {
			jQuery.ajax({ 
				type: "POST", 
				url: "showAll.do", 
				data: {"path":treeNode.path}, 
				success: function(msg) {
				  $("#flist").empty();
				  var li="";
				  var jsonData = eval(msg);//接收到的数据转化为JQuery对象,由JQuery为我们处理  
	                $.each(jsonData, function(index, objVal) { //遍历对象数组,index是数组的索引号,objVal是遍历的一个对象。 
	                	if(objVal["icon"]!="folder.png"){
						li+="<li><a href='showChildren.do?path="+objVal["path"]+"'   title='文件名:"+objVal["name"]+"
大小:"+objVal["len"]+"
修改时间:"+objVal["time"]+"
所有者:"+objVal["owner"]+"
份数:"+objVal["replication"]+"
块大小:"+objVal["blockSize"]+"
所在组:"+objVal["group"]+"'  ><img src='${request.contextPath}/static/icon/"+objVal["icon"]+"'></a><a href='showChildren.do?path="+objVal["path"]+"'   class='wenzi'  title='文件名:"+objVal["name"]+"
大小:"+objVal["len"]+"
修改时间:"+objVal["time"]+"
所有者:"+objVal["owner"]+"
份数:"+objVal["replication"]+"
块大小:"+objVal["blockSize"]+"
所在组:"+objVal["group"]+"'>"+objVal["name"].substring(0,8)+"</a><p></p><a data-toggle='modal' href='#example'  οnclick=\"previewFiles('"+objVal['path']+"')\"  style='width:100%;text-align:center;'>预览</a></li>";
	               			}else{
							li+="<li><a href='javascript:void(0);'  οnclick=\"showChildren('"+objVal["path"]+"')\"  title='文件名:"+objVal["name"]+"
大小:"+objVal["len"]+"
修改时间:"+objVal["time"]+"
所有者:"+objVal["owner"]+"
份数:"+objVal["replication"]+"
块大小:"+objVal["blockSize"]+"
所在组:"+objVal["group"]+"'   ><img src='${request.contextPath}/static/icon/"+objVal["icon"]+"'></a><a href='javascript:void(0);' οnclick=\"showChildren('"+objVal["path"]+"')\"  class='wenzi'  title='文件名:"+objVal["name"]+"
大小:"+objVal["len"]+"
修改时间:"+objVal["time"]+"
所有者:"+objVal["owner"]+"
份数:"+objVal["replication"]+"
块大小:"+objVal["blockSize"]+"
所在组:"+objVal["group"]+"'>"+objVal["name"].substring(0,8)+"</a></li>";
	                	}
	                });
	                $("#flist").append(li);
				}
			}); 
		}
		function previewFiles(path){
		    	jQuery.ajax({ 
				type: "post", 
				url: "previewFile.do", 
				data: {"path":path}, 
				success: function(msg) {
					var suffix=path.substring(path.lastIndexOf(".")+1,path.length);
					if(suffix=="gif"||suffix=="png"||suffix=="jpg"||suffix=="jpeg"){
						$("#content").html("");
						$("#content").append("<img src='previewFile.do?path="+path+"'/>");
					}else{
						$("#content").html(msg);
					}
				}
			}); 
        }
        function showChildren(path){
	        jQuery.ajax({ 
				type: "post", 
				url: "showAll.do", 
				data: {"path":path}, 
				success: function(msg) {
				  $("#flist").empty();
				  var li="";
				  var jsonData = eval(msg);//接收到的数据转化为JQuery对象,由JQuery为我们处理  
	                $.each(jsonData, function(index, objVal) { //遍历对象数组,index是数组的索引号,objVal是遍历的一个对象。  
						if(objVal["icon"]!="folder.png"){
						li+="<li><a  href='showChildren.do?path="+objVal["path"]+"' title='文件名:"+objVal["name"]+"
大小:"+objVal["len"]+"
修改时间:"+objVal["time"]+"
所有者:"+objVal["owner"]+"
份数:"+objVal["replication"]+"
块大小:"+objVal["blockSize"]+"
所在组:"+objVal["group"]+"' ><img src='${request.contextPath}/static/icon/"+objVal["icon"]+"'></a><a href='showChildren.do?path="+objVal["path"]+"'   class='wenzi'  title='文件名:"+objVal["name"]+"
大小:"+objVal["len"]+"
修改时间:"+objVal["time"]+"
所有者:"+objVal["owner"]+"
份数:"+objVal["replication"]+"
块大小:"+objVal["blockSize"]+"
所在组:"+objVal["group"]+"'>"+objVal["name"].substring(0,8)+"</a><p></p><a data-toggle='modal' href='#example'  οnclick=\"previewFiles('"+objVal['path']+"')\"  style='width:100px;text-align:center;'>预览</a></li>";
	               			}else{
						li+="<li><a  href='javascript:void(0);' οnclick=\"showChildren('"+objVal["path"]+"')\" title='文件名:"+objVal["name"]+"
大小:"+objVal["len"]+"
修改时间:"+objVal["time"]+"
所有者:"+objVal["owner"]+"
份数:"+objVal["replication"]+"
块大小:"+objVal["blockSize"]+"
所在组:"+objVal["group"]+"' οnclick='children("+objVal["path"]+")' ><img src='${request.contextPath}/static/icon/"+objVal["icon"]+"'></a><a href='javascript:void(0);' οnclick=\"showChildren('"+objVal["path"]+"')\"   class='wenzi'  title='文件名:"+objVal["name"]+"
大小:"+objVal["len"]+"
修改时间:"+objVal["time"]+"
所有者:"+objVal["owner"]+"
份数:"+objVal["replication"]+"
块大小:"+objVal["blockSize"]+"
所在组:"+objVal["group"]+"'>"+objVal["name"].substring(0,8)+"</a></li>";
	                	}	                });
	                $("#flist").append(li);
				}
			}); 
        }
		function createTree () {
			var zNodes = dataMaker(10000);
			showNodeCount = 0;
			$("#treeDemo").empty();
			setting.check.enable = $("#showChk").attr("checked");
			var tree=$.fn.zTree.init($("#treeDemo"), setting, zNodes);
			tree.expandAll(true);
		}

		$(document).ready(function(){
			ruler.init("ruler");
			createTree();

		});
	</script> 
  <style type="text/css">
*{margin:0; padding:0;}
*{font-family:"FontAwesome","微软雅黑"!important}
p{width:100%;text-align:center}
#files{height:650px;margin:11px 0px 0px -8px;padding:5px; position:relative;width:1240px;background-color: #F0F6E4;}
#files ul{list-style-type:none; zoom:1;width:100%;height:450px;overflow-y:scroll;}
#files ul li{float:left; margin:10px; list-style: none;width:100px;text-align:center;}
#files ul li a img{width:80px; height:80px; padding:5px;border:0;display:block;}
#files ul li a.wenzi{line-height:20px; text-align:center;black; display:block; overflow: hidden; width:100px;}
</style> 
 </head> 
 <body> 
 <input type="hidden" id="image" value="${image}"/>
  <div class="container-fluid"> 
     <span class="glyphicon glyphicon-chevron-left"></span>
 	 <span class="glyphicon glyphicon-chevron-right"></span>
   <ol class="breadcrumb">
             文件路径 
    <li><a href="#">hdfs://192.168.0.187:8020/home/cc/file/</a></li> 
    <li class="active">${path}</li>
   </ol> 
   
   <div class="span3 file"> 
    <div class="zTreeDemoBackground"> 
     <ul id="treeDemo" class="ztree">
     </ul> 
    </div> 
   </div> 
   <div class="span9 file" id="files"> 
    <ul id="flist" > 
    </ul> 
    <hr>
	<div style="width:99%; height:200px; bottom: 0px;position: absolute;overflow-y:scroll;">
		<p>预览区</p>
		<div id="content"></div>
	</div>    
   </div> 
 	<ol class="breadcrumb">
	    <li>${descr}</li> 
    </ol> 
  </div> 
  <input type="hidden" value="${treestr}" id="tree" />   
 </body>
</html>
这个功能使用spring+mvc框架实现的,语言叙述的不清晰,做个记录,以便日后用到。
求大神指点,毕竟新人
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值