分享

hadoop网盘小项目介绍及相关代码下载2

desehawk 发表于 2014-12-3 21:21:54 [显示全部楼层] 只看大图 回帖奖励 阅读模式 关闭右栏 22 70250
本帖最后由 pig2 于 2014-12-9 15:39 编辑
问题导读



1.如何调用hadoop api实现文件的上传、下载、删除、创建目录和显示功能?
2.结合web前台和hadoop api结合点在什么地方?







一、调用hadoop api实现文件的上传、下载、删除、创建目录和显示功能
(1)添加必要的hadoop jar包。

A、首先将Hadoop1.1.2.tar.gz解压到某一个磁盘下。
B、右键选择工程,选择build path...., build configure path;
C、将hadoop1.1.2文件夹下的jar包添加进去;


1.png


还有lib文件夹下的所有jar包(注意:jasper-compiler-5.5.12.jar和jasper-runtime-5.5.12.jar不要引进,否则会报错)


2.png


3.png


注意:在build path引入这些jar包后,还需要将这些jar包复制到WEB-INF/lib目录下,可以通过下面操作实现:
选择工程,右键“Properties”,选择Deployment Assembly。
点击Add,选择Java Build Path Entries。


x1.png


然后把你刚刚引进的Jar包全部选上,点击finishes。


4.png


D 、创建java工程
创建HdfsDAO类:


  1. package com.model;
  2. import java.io.IOException;
  3. import java.net.URI;
  4. import org.apache.hadoop.conf.Configuration;
  5. import org.apache.hadoop.fs.FileStatus;
  6. import org.apache.hadoop.fs.FileSystem;
  7. import org.apache.hadoop.fs.Path;
  8. import org.apache.hadoop.mapred.JobConf;
  9. public class HdfsDAO {
  10.     //HDFS访问地址
  11.     private static final String HDFS = "hdfs://192.168.1.104:9000";
  12.    
  13.     public HdfsDAO(Configuration conf) {
  14.         this(HDFS, conf);
  15.     }
  16.     public HdfsDAO(String hdfs, Configuration conf) {
  17.         this.hdfsPath = hdfs;
  18.         this.conf = conf;
  19.     }
  20.     //hdfs路径
  21.     private String hdfsPath;
  22.     //Hadoop系统配置
  23.     private Configuration conf;
  24.      
  25.    
  26.     //启动函数
  27.     public static void main(String[] args) throws IOException {
  28.         JobConf conf = config();
  29.         HdfsDAO hdfs = new HdfsDAO(conf);
  30.         //hdfs.mkdirs("/Tom");
  31.         //hdfs.copyFile("C:\\files", "/wgc/");
  32.          hdfs.ls("hdfs://192.168.1.104:9000/wgc/files");
  33.         //hdfs.rmr("/wgc/files");
  34.         //hdfs.download("/wgc/(3)windows下hadoop+eclipse环境搭建.docx", "c:\");
  35.         //System.out.println("success!");
  36.     }        
  37.    
  38.     //加载Hadoop配置文件
  39.     public  static JobConf config(){
  40.         JobConf conf = new JobConf(HdfsDAO.class);
  41.         conf.setJobName("HdfsDAO");
  42.         conf.addResource("classpath:/hadoop/core-site.xml");
  43.         conf.addResource("classpath:/hadoop/hdfs-site.xml");
  44.         conf.addResource("classpath:/hadoop/mapred-site.xml");
  45.         return conf;
  46.     }
  47.     //在根目录下创建文件夹
  48.     public void mkdirs(String folder) throws IOException {
  49.         Path path = new Path(folder);
  50.         FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);
  51.         if (!fs.exists(path)) {
  52.             fs.mkdirs(path);
  53.             System.out.println("Create: " + folder);
  54.         }
  55.         fs.close();
  56.     }
  57.    
  58.     //某个文件夹的文件列表
  59.     public FileStatus[] ls(String folder) throws IOException {
  60.         Path path = new Path(folder);
  61.         FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);
  62.         FileStatus[] list = fs.listStatus(path);
  63.         System.out.println("ls: " + folder);
  64.         System.out.println("==========================================================");
  65.         if(list != null)
  66.         for (FileStatus f : list) {
  67.             //System.out.printf("name: %s, folder: %s, size: %d\n", f.getPath(), f.isDir(), f.getLen());
  68.                 System.out.printf("%s, folder: %s, 大小: %dK\n", f.getPath().getName(), (f.isDir()?"目录":"文件"), f.getLen()/1024);
  69.         }
  70.         System.out.println("==========================================================");
  71.         fs.close();
  72.         
  73.         return  list;
  74.     }
  75.    
  76.    
  77.     public void copyFile(String local, String remote) throws IOException {
  78.         FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);
  79.         //remote---/用户/用户下的文件或文件夹
  80.         fs.copyFromLocalFile(new Path(local), new Path(remote));
  81.          System.out.println("copy from: " + local + " to " + remote);
  82.         fs.close();
  83.     }
  84.    
  85.     //删除文件或文件夹
  86.     public void rmr(String folder) throws IOException {
  87.         Path path = new Path(folder);
  88.         FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);
  89.         fs.deleteOnExit(path);
  90.         System.out.println("Delete: " + folder);
  91.         fs.close();
  92.     }
  93.    
  94.    
  95.     //下载文件到本地系统
  96.     public void download(String remote, String local) throws IOException {
  97.         Path path = new Path(remote);
  98.         FileSystem fs = FileSystem.get(URI.create(hdfsPath), conf);
  99.         fs.copyToLocalFile(path, new Path(local));
  100.         System.out.println("download: from" + remote + " to " + local);
  101.         fs.close();
  102.     }
  103.    
  104.    
  105. }
复制代码




5.png


在测试前,请启动hadoop;

运行测试该程序:

6.png

其他函数测试也成功,这里就不一一列举了。

二、结合web前台和hadoop api
打开Uploadservlet文件,修改:
  1. package com.controller;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.util.Iterator;
  5. import java.util.List;
  6. import javax.servlet.ServletContext;
  7. import javax.servlet.ServletException;
  8. import javax.servlet.http.HttpServlet;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import javax.servlet.<a href="http://www.it165.net/pro/webjsp/" target="_blank" class="keylink">jsp</a>.PageContext;
  12. import org.apache.commons.fileupload.DiskFileUpload;
  13. import org.apache.commons.fileupload.FileItem;
  14. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  15. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  16. import org.apache.hadoop.fs.FileStatus;
  17. import org.apache.hadoop.mapred.JobConf;
  18. import com.model.HdfsDAO;
  19. /**
  20. * Servlet implementation class UploadServlet
  21. */
  22. public class UploadServlet extends HttpServlet {
  23.         /**
  24.          * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  25.          */
  26.         protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  27.                 this.doPost(request, response);
  28.         }
  29.         /**
  30.          * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  31.          */
  32.         protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  33.                    request.setCharacterEncoding("UTF-8");
  34.                    File file ;
  35.                    int maxFileSize = 50 * 1024 *1024;  //50M
  36.                    int maxMemSize = 50 * 1024 *1024;    //50M
  37.                    ServletContext context = getServletContext();
  38.                    String filePath = context.getInitParameter("file-upload");
  39.                         System.out.println("source file path:"+filePath+"");
  40.                    // 验证上传内容了类型
  41.                    String contentType = request.getContentType();
  42.                    if ((contentType.indexOf("multipart/form-data") >= 0)) {
  43.                       DiskFileItemFactory factory = new DiskFileItemFactory();
  44.                       // 设置内存中存储文件的最大值
  45.                       factory.setSizeThreshold(maxMemSize);
  46.                       // 本地存储的数据大于 maxMemSize.
  47.                       factory.setRepository(new File("c:\\temp"));
  48.                       // 创建一个新的文件上传处理程序
  49.                       ServletFileUpload upload = new ServletFileUpload(factory);
  50.                       // 设置最大上传的文件大小
  51.                       upload.setSizeMax( maxFileSize );
  52.                       try{
  53.                          // 解析获取的文件
  54.                          List fileItems = upload.parseRequest(request);
  55.                          // 处理上传的文件
  56.                          Iterator i = fileItems.iterator();
  57.                          System.out.println("begin to upload file to tomcat server</p>");
  58.                          while ( i.hasNext () )
  59.                          {
  60.                             FileItem fi = (FileItem)i.next();
  61.                             if ( !fi.isFormField () )        
  62.                             {
  63.                             // 获取上传文件的参数
  64.                             String fieldName = fi.getFieldName();
  65.                             String fileName = fi.getName();
  66.                            
  67.                             String fn = fileName.substring( fileName.lastIndexOf("\")+1);
  68.                             System.out.println("<br>"+fn+"<br>");
  69.                             boolean isInMemory = fi.isInMemory();
  70.                             long sizeInBytes = fi.getSize();
  71.                             // 写入文件
  72.                             if( fileName.lastIndexOf("\") >= 0 ){
  73.                             file = new File( filePath ,
  74.                             fileName.substring( fileName.lastIndexOf("\"))) ;
  75.                             //out.println("filename"+fileName.substring( fileName.lastIndexOf("\"))+"||||||");
  76.                             }else{
  77.                             file = new File( filePath ,
  78.                             fileName.substring(fileName.lastIndexOf("\")+1)) ;
  79.                             }
  80.                             fi.write( file ) ;
  81.                             System.out.println("upload file to tomcat server success!");
  82.                            
  83. System.out.println("begin to upload file to hadoop hdfs</p>");
  84.                             //将tomcat上的文件上传到hadoop上
  85.                            
  86.                             JobConf conf = HdfsDAO.config();
  87.                             HdfsDAO hdfs = new HdfsDAO(conf);
  88.                             hdfs.copyFile(filePath+"\"+fn, "/wgc/"+fn);
  89.                             System.out.println("upload file to hadoop hdfs success!");
  90.                                     
  91.                             request.getRequestDispatcher("index.<a href="http://www.it165.net/pro/webjsp/" target="_blank" class="keylink">jsp</a>").forward(request, response);
  92.                            
  93.                             }
  94.                          }
  95.                       }catch(Exception ex) {
  96.                          System.out.println(ex);
  97.                       }
  98.                    }else{
  99.                       System.out.println("<p>No file uploaded</p>");
  100.                
  101.                    }
  102.          
  103.               
  104.                  
  105.         }
  106. }
复制代码






启动tomcat服务器测试:
在上传前,hdfs下的wgc文件夹列表如下:


7.png


接下来我们上传:(4)通过调用hadoop的java api实现本地文件上传到hadoop文件系统上.docx


8.png


在tomcat服务器上,我们可以看到刚刚上传的文件:


9.png


打开http://hadoop:50070/查看文件系统,可以看到新上传的文件:


10.png



那么,到此,一个简陋的网盘上传功能就实现了,接下来我们就对这个简陋的网盘做一些美工,让它看起来更漂亮些。



网盘代码地址.rar (166 Bytes, 下载次数: 66, 售价: 8 云币)

已有(22)人评论

跳转到指定楼层
liusiping 发表于 2014-12-3 22:26:53
回复

使用道具 举报

zhang 发表于 2014-12-4 09:06:05
回复

使用道具 举报

zhang 发表于 2014-12-4 09:06:36
学习中         
回复

使用道具 举报

wubaozhou 发表于 2014-12-28 16:57:15
回复

使用道具 举报

yxb3158 发表于 2015-1-15 23:33:43
云币不够怎么办?
回复

使用道具 举报

plist 发表于 2015-1-28 09:33:44
这个必须看看啊,
回复

使用道具 举报

gh_rainbow 发表于 2015-1-29 21:55:08
好例子,收藏了。
回复

使用道具 举报

winfys 发表于 2015-3-10 00:35:07
回复

使用道具 举报

ainubis 发表于 2015-4-5 03:00:14
回复

使用道具 举报

123下一页
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条