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

70 篇文章 0 订阅
47 篇文章 0 订阅

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

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

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

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


[java]  view plain copy 在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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值