2014-10-06 78 views
9

我想写一个MapReduce程序,它可以读取输入文件并将输出写入另一个文本文件。我打算为此使用BufferedReader类。但我真的不知道如何在MapReduce程序中使用它。Hadoop Map Reduce读取文本文件

有人可以给我一个它的代码片段吗?

P.S.我完全不熟悉Hadoop和MapReduce编程。所以请耐心等待。

预先感谢您。

+0

直到现在你尝试了什么?以及你正在努力实现什么。请具体说明。你想读取用户的输入文件并将输出写入HDFS?你能再解释一下吗? – 2014-10-06 04:32:00

+0

@SreeVeni好吧,在这里。我想用BufferedReader读取文本文件。我想将输出写入HDFS(最好)或将输出写入另一个文本文件。我还没有真正尝试过任何东西。但这正是我基本想要做的。我已经通过互联网查看了示例代码片段,但无法找到我的问题的答案。你能帮我吗? – user2201650 2014-10-06 04:37:43

+0

再一次澄清你想从HDFS中读取文本文件吗? – 2014-10-06 04:50:45

回答

7

下面的代码可以帮助你阅读从HDFS文件,并显示在控制台

import java.io.BufferedReader; 
import java.io.InputStreamReader; 

import org.apache.hadoop.conf.Configuration; 
import org.apache.hadoop.fs.FileSystem; 
import org.apache.hadoop.fs.Path; 

public class Cat{ 
    public static void main (String [] args) throws Exception{ 
     try{ 
      Path pt=new Path("hdfs:/path/to/file");//Location of file in HDFS 
      FileSystem fs = FileSystem.get(new Configuration()); 
      BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(pt))); 
      String line; 
      line=br.readLine(); 
      while (line != null){ 
       System.out.println(line); 
       line=br.readLine(); 
      } 
     }catch(Exception e){ 
     } 
    } 
} 

编辑

驱动

public class ReadFile { 

    public static void main(String[] args) throws Exception { 
     Configuration conf = new Configuration(); 
     Job job = new Job(conf, "Read a File"); 


     FileSystem fs = FileSystem.get(conf); 
     job.setOutputKeyClass(Text.class); 
     job.setOutputValueClass(IntWritable.class); 
     if (fs.exists(new Path(args[1]))) 
      fs.delete(new Path(args[1]), true); 
     job.setMapperClass(Map.class); 
     job.setReducerClass(Reduce.class); 

     job.setInputFormatClass(TextInputFormat.class); 
     job.setOutputFormatClass(TextOutputFormat.class); 

     FileInputFormat.addInputPath(job, new Path(args[0])); 
     FileOutputFormat.setOutputPath(job, new Path(args[1])); 
     job.setJarByClass(ReadFile.class);  
     job.waitForCompletion(true); 
    } 

} 

映射

public class Map extends Mapper<LongWritable, Text, Text, IntWritable> { 

    public void setup(Context context) throws IOException{ 
     Path pt=new Path("hdfs:/path/to/file");//Location of file in HDFS 
     FileSystem fs = FileSystem.get(new Configuration()); 
     BufferedReader br=new BufferedReader(new InputStreamReader(fs.open(pt))); 
     String line; 
     line=br.readLine(); 
     while (line != null){ 
      System.out.println(line); 
      line=br.readLine(); 
     } 
    } 
    public void map(LongWritable key, Text value, Context context) 
      throws IOException, InterruptedException { 
     //as your wish 
     } 
    } 
} 
内容

上面的代码可以帮助您从HDFS中读取文本文件。

+0

更新感谢您的代码片段。但我试过这个。我想要的是读取map-reduce样式程序中的文本文件。即使用映射器和减速器类。 – user2201650 2014-10-06 16:18:26

+0

您是否知道在map-reduce样式程序中读取文本文件的人员?因为那是我需要做的。如果你能告诉我该怎么做,这将非常有帮助。先谢谢你! – user2201650 2014-10-06 19:32:05

+0

@ user2201650:看我的编辑 – 2014-10-07 04:24:49