码迷,mamicode.com
首页 > 其他好文 > 详细

[hadoop]hadoop权威指南例第二版3-1、3-2

时间:2014-08-16 11:09:30      阅读:377      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   java   使用   os   io   

hadoop版本1.2.1

jdk1.7.0

 

例3-1、通过URLStreamHandler实例以标准输出方式显示Hadoop文件系统的文件

hadoop fs -mkdir input

在本地创建两个文件file1,file2,file1的内容为hello world,file2内容为hello Hadoop,然后上传到input,具体方法如Hadoop集群(第6期)_WordCount运行详解中 2.1、准备工作可以看到。

 

完整代码如下:

 1 import org.apache.hadoop.fs.FsUrlStreamHandlerFactory;
 2 import org.apache.hadoop.io.IOUtils;
 3 import java.net.URL;
 4 import java.io.InputStream;
 5 
 6 public class URLCat{
 7         static {
 8                 URL.setURLStreamHandlerFactory(new FsUrlStreamHandlerFactory());
 9         }
10         public static void main(String[] args) throws Exception {
11                 InputStream in = null;
12                 try{
13                         in = new URL(args[0]).openStream();
14                         IOUtils.copyBytes(in,System.out,4096,false);
15                 }
16                 finally{
17                         IOUtils.closeStream(in);
18                 }
19         }
20 }

 

编译生成class文件,打包成jar文件,打包方法在[hadoop]命令行编译并运行hadoop例子WordCount有详细讲述。

然后使用命令

hadoop jar URLCat.jar URLCat hdfs://localhost:9000/usr/hadoop/input/file1
hdfs://localhost:9000是HDFS文件系统的名字,在conf/core-site.xml中有设置

运行结果

hadoop@Mint ~/hadoop-1.2.1/classes $ hadoop jar URLCat.jar URLCat hdfs://localhost:9000/user/hadoop/input/file1
hello world

 例3-2、直接使用FileSystem以标准输出格式显示Hadoop文件系统中的文件

完整代码

 1 import org.apache.hadoop.conf.Configuration;
 2 import org.apache.hadoop.fs.FileSystem;
 3 import org.apache.hadoop.fs.Path;
 4 import java.net.URI;
 5 import java.net.URL;
 6 import java.io.InputStream;
 7 import org.apache.hadoop.io.IOUtils;
 8 
 9 public class FileSystemCat {
10     public static void main(String[] args) throws Exception {
11         String uri = args[0];
12         Configuration conf = new Configuration();
13         FileSystem fs = FileSystem.get(URI.create(uri), conf);
14         InputStream in = null;
15         try {
16             in = fs.open(new Path(uri));
17             IOUtils.copyBytes(in, System.out, 4096, false);
18         } finally {
19             IOUtils.closeStream(in);
20         }
21     }
22 }

同理编译打包运行实例

hadoop jar FileSystemCat.jar FileSystemCat hdfs:locahost:9000/user/hadoop/input/file2

结果显示

hadoop@Mint ~/hadoop-1.2.1/classes $ hadoop jar FileSystemCat.jar FileSystemCat hdfs://localhost:9000/user/hadoop/input/file1
hello hadoop

 

bubuko.com,布布扣
本文基于知识共享署名-非商业性使用 3.0 许可协议进行许可。欢迎转载、演绎,但是必须保留本文的署名林羽飞扬,若需咨询,请给我发信

[hadoop]hadoop权威指南例第二版3-1、3-2,布布扣,bubuko.com

[hadoop]hadoop权威指南例第二版3-1、3-2

标签:style   blog   http   color   java   使用   os   io   

原文地址:http://www.cnblogs.com/zhengyuhong/p/3916151.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!