hadoop第一个程序PutMerge

来源:互联网 发布:c语言五子棋游戏源代码 编辑:程序博客网 时间:2024/05/16 05:58

前一阵子没有继续学习hadoop了,有些生疏,今天重新开始学习,跟着《Hadoop in Action》书上敲下了第一个程序PutMerge。该PutMerge程序旨在将本地文件合并后放入HDFS系统。

其基本步骤为:

  1. 根据用户定义的参数设置本地目录和HDFS的目标文件
     Configuration conf = new Configuration();
     FileSystem hdfs =  FileSystem.get(conf);//HDFS接口的FileSystem对象
     FileSystem local = FileSystem.getLocal(conf);//本地文件系统的FileSystem对象
  2. 提取本地输入目录中的每个文件信息
     Path inputDir = new Path(args[0]);//上传目录
     Path hdfsFile = new Path(args[1]);//目的目录
     FileStatus[] inputFiles = local.listStatus(inputDir);//本地文件列表
  3. 创建输出流写入到HDFS文件系统
    FSDataOutputStream out = hdfs.create(hdfsFile);//HDFS的输出流
  4. 遍历本地目录的每个文件打开输入流读取该文件。
    FSDataInputStream in = local.open(inputFiles[i].getPath());//本地输入流
    byte buffer[] = new  byte[256];
    int bytesRead = 0;
    while((bytesRead = in.read(buffer)) > 0){
      out.write(buffer,0,bytesRead);
    }
代码如下:
  1 import java.io.IOException;  2 import org.apache.hadoop.conf.Configuration;  3 import org.apache.hadoop.fs.*;  4   5 public class PutMerge{  6     public static void main(String[] args)throws IOException{  7         Configuration conf = new Configuration();  8         FileSystem hdfs =  FileSystem.get(conf);  9         FileSystem local = FileSystem.getLocal(conf); 10  11         Path inputDir = new Path(args[0]); 12         Path hdfsFile = new Path(args[1]); 13  14         try{ 15             FileStatus[] inputFiles = local.listStatus(inputDir); 16             FSDataOutputStream out = hdfs.create(hdfsFile); 17  18             for(int i=0; i<inputFiles.length; i++) 19             { 20                 System.out.println(inputFiles[i].getPath().getName()); 21                 FSDataInputStream in = local.open(inputFiles[i].getPath()); 22                 byte buffer[] = new  byte[256]; 23                 int bytesRead = 0; 24                 while((bytesRead = in.read(buffer)) > 0){ 25                     out.write(buffer,0,bytesRead); 26                 } 27                 in.close(); 28             } 29             out.close(); 30         }catch(IOException e){ 31             e.printStackTrace(); 32         } 33     } 34 }
编译:
javac -classpath hadoop-0.20.2-core.jar:lib/commons-cli-1.2.jar -d playground/classes playground/src/PutMerge.java
查看生成的文件:
ls playground/classes/
打包:
jar -cvf PutMerge.jar PutMerge.class 
HDFS文件系统上建立putmerge文件夹:
bin/hadoop fs -mkdir putmerge
上传本地test文件夹下的a.txt~c.txt到putmerge文件夹下的sum.txt:
 bin/hadoop jar playground/classes/PutMerge.jar PutMerge test/ putmerge/sum.txt
查看结果:
bin/hadoop fs -cat putmerge/sum.txt
查看结果可知本地文件夹确实已经合并并上传了。实验成功!

0 0
原创粉丝点击