Hadoop第一个程序,利用API向HDFS中写入数据

来源:互联网 发布:安卓手机定位软件 编辑:程序博客网 时间:2024/06/04 23:24

参考:http://f.dataguru.cn/thread-85493-1-1.html

这时学习Hadoop以来写的第一个成功的程序,程序仿照《Hadoop实战》中的PutMerge程序,这里有几个要注意的地方:

1.hdfs的地址是一个网络地址,如下面的:hdfs://localhost:9000/test3

2.确保不会出现“权限不足”的异常


[java] view plaincopy在CODE上查看代码片派生到我的代码片
  1. import java.io.IOException;  
  2. import java.net.URI;  
  3.   
  4. import org.apache.hadoop.conf.Configuration;  
  5. import org.apache.hadoop.fs.FSDataInputStream;  
  6. import org.apache.hadoop.fs.FSDataOutputStream;  
  7. import org.apache.hadoop.fs.FileStatus;  
  8. import org.apache.hadoop.fs.FileSystem;  
  9. import org.apache.hadoop.fs.Path;  
  10. /** 
  11.  *  
  12.  */  
  13.   
  14. /** 
  15.  * Hadoop版本1.2.1 
  16.  * 系统ubuntu 12.04 
  17.  * JDK 1.7 
  18.  * 
  19.  */  
  20. public class PutMerge {  
  21.   
  22.     public static void main(String[] args) throws IOException {  
  23.           
  24.         Configuration conf = new Configuration();  
  25.           
  26.         Path inputDir = new Path("/home/hadoop/input");  
  27.         String serverPath = "hdfs://localhost:9000/test3";  
  28.         Path hdfsfile = new Path(serverPath);  
  29.           
  30.         FileSystem hdfs = FileSystem.get(URI.create(serverPath), conf);  
  31.         FileSystem local = FileSystem.getLocal(conf);  
  32.         FileStatus[] status = local.listStatus(inputDir);  
  33.         FSDataOutputStream out = hdfs.create(hdfsfile);  
  34.           
  35.         for(int i = 0; i < status.length; i++) {  
  36.             FSDataInputStream in = local.open(status[i].getPath());  
  37.             byte buffer[] = new byte[256];  
  38.             int byteread = 0;  
  39.             while((byteread = in.read(buffer)) > 0) {  
  40.                 out.write(buffer);  
  41.             }  
  42.             in.close();  
  43.         }  
  44.         out.close();  
  45.     }  
  46.   
  47. }  
原文地址:点击打开链接
0 0
原创粉丝点击