MapReduce:根据文件中的模式将文本文件拆分为多个文件

时间:2013-02-18 09:40:37

标签: mapreduce

我有一个标签分隔的.txt文件,如下所示:

  

05-12-2011 02:00:00 XYZZ

     

05-12-2011 02:01:00 XYZZ

     

05-12-2011 02:02:00 XYZZ

     

05-12-2011 02:03:00 XYZZ

     

05-12-2011 02:04:00 ABCD

     

05-12-2011 02:05:00 ABCD

     

05-12-2011 02:06:00 ABCD

     

05-12-2011 02:07:00 XYZZ

     

05-12-2011 02:08:00 ABCD

我想将数据写入不同的文件,例如带有“XYZZ”模式的文件到一个文件中,把那些带有“ABCD”的文件写入另一个文件。

file1.txt将包含:

  

05-12-2011 02:01:00 XYZZ

     

05-12-2011 02:02:00 XYZZ

     

05-12-2011 02:03:00 XYZZ

     

05-12-2011 02:07:00 XYZZ

file2.txt将包含:

  

05-12-2011 02:04:00 ABCD

     

05-12-2011 02:05:00 ABCD

     

05-12-2011 02:06:00 ABCD

这是我要分享的代码。

public class WordCount2 {

  public static class TokenizerMapper2
       extends Mapper<Object, Text, Text, IntWritable>{

        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();

    public void map(Object key, Text value, Context context
                    ) throws IOException, InterruptedException {
      StringTokenizer itr = new StringTokenizer(value.toString());
      while (itr.hasMoreTokens()) {
        word.set(itr.nextToken());
        context.write(word, one);
      }
    }
  }

  public static class IntSumReducer2
       extends Reducer<Text,IntWritable,Text,IntWritable> {
    private IntWritable result = new IntWritable();

    public void reduce(Text key, Iterable<IntWritable> values, 
                       Context context
                       ) throws IOException, InterruptedException {
    /*  int sum = 0;
      for (IntWritable val : values) {
        sum += val.get();
      }
      result.set(sum);
      context.write(key, result);*/
    }
  }

  public static void main(String[] args) throws Exception {

    Configuration conf = new Configuration();
    String line; 
    String arguements[];
    String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();

    // calculating the total number of attributes in the file
    FileReader infile = new FileReader(args[0]);
    BufferedReader bufread = new BufferedReader(infile);
    line = bufread.readLine();
    arguements = line.split(","); //for spliting fields separated by comma
    conf.setInt("argno", arguements.length); // saving that attribute value

    Job job = new Job(conf, "word count");
    job.setJarByClass(WordCount.class);
    job.setMapperClass(TokenizerMapper.class);
    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);
    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);
    FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
    FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
    System.exit(job.waitForCompletion(true) ? 0 : 1);
  }
}

0 个答案:

没有答案