<p>package selfname;</p> import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; //import org.apache.hadoop.mapreduce.lib.input.CombineFileInputFormat; //import org.apache.hadoop.mapreduce.lib.input.MultipleTextOutputFormat; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs; public class Selfname { public static class FileMap extends Mapper<Object,Text,Text,Text>{ public void map(Object key,Text value,Context context) throws IOException, InterruptedException{ String line = value.toString(); if(line.length()>=93){ String keys = line.substring(15, 19); String values = line.substring(87,93); context.write(new Text(keys), new Text(values)); } } } public static class FileReduce extends Reducer<Text,Text,Text,Text>{ <strong>private MultipleOutputs<Text, Text> multipleOutputs; protected void setup(Context context)throws IOException, InterruptedException { multipleOutputs = new MultipleOutputs<Text, Text>(context); }</strong> public void reduce(Text key,Iterable<Text>values,Context context) throws IOException, InterruptedException{ String value = new String(); for(Text val:values){ value+=val.toString()+","; } <strong>multipleOutputs.write(key, new Text(value), key.toString());</strong> } <strong>protected void cleanup(Context context)throws IOException, InterruptedException { multipleOutputs.close(); }</strong> } public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException{ Configuration conf = new Configuration(); Job job = new Job(conf,"myfile"); job.setJarByClass(Selfname.class); job.setMapperClass(FileMap.class); job.setReducerClass(FileReduce.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setNumReduceTasks(1); FileInputFormat.addInputPath(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true)?0:1); } }
上面的代码实现了自定义的输出文件名,关键部分由粗体字标出。
使用MultipleOutputs类动态的实现输出文件的命名,动态,灵活。可以满足用户的定制需求,而且相对与其他的方法其代码量也非常少。
这里我用的数据是权威指南上边的气象数据,将相同年份的气温存储到一个文件中。
<strong>private MultipleOutputs<Text, Text> multipleOutputs;</strong>
<strong>声明一个MultipleOutputs变量。</strong>
<strong></strong><pre name="code" class="java"><strong>protected void setup(Context context)throws IOException, InterruptedException { multipleOutputs = new MultipleOutputs<Text, Text>(context); }</strong>
创建一个MultipleOutput变量。
<strong></strong><pre name="code" class="java"><strong>multipleOutputs.write(key, new Text(value), key.toString());</strong>
输出文件,类似于context.write。第一个变量为key,第二个变量为value,第三个变量为输出文件路径名。
<strong>最后需要使用cleanup函数将这个对象关闭。</strong>
<strong> </strong>
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-16 05:52:20