我有一个制表符分隔的 .txt 文件,如下所示:
05-12-2011 02:00:00 XYZZ
05-12-2011 02:01:00
05-12-2011 02:02:00
05-12-2011 02:03:00
05-12-2011 02:04:00 ABCD
2011 年 5 月 12 日 02:05:00 ABCD
2011 年 5 月 12 日 02:06:00 ABCD
2011 年 5 月 12 日 02:07:00
2011 年 5 月 12 日 02:08:00 ABCD
我想将数据写入不同的文件,例如将模式为“XYZZ”的文件写入一个文件,将带有“ABCD”的文件写入另一个文件。
file1.txt 将包含:
05-12-2011 02:01:00
05-12-2011 02:02:00
05-12-2011 02:03:00
2011 年 5 月 12 日 02:07:00
file2.txt 将包含:
05-12-2011 02:04:00 ABCD
2011 年 5 月 12 日 02:05:00 ABCD
2011 年 5 月 12 日 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);
}
}