在一般情況下,Hadoop 每一個(gè) Reducer 產(chǎn)生一個(gè)輸出文件,文件以
part-r-00000、part-r-00001 的方式進(jìn)行命名。如果需要人為的控制輸出文件的命
名或者每一個(gè) Reducer 需要寫(xiě)出多個(gè)輸出文件時(shí),可以采用 MultipleOutputs 類(lèi)來(lái)
完成。MultipleOutputs 采用輸出記錄的鍵值對(duì)(output Key 和 output Value)或者
任意字符串來(lái)生成輸出文件的名字,文件一般以 name-r-nnnnn 的格式進(jìn)行命名,
其中 name 是程序設(shè)置的任意名字;nnnnn 表示分區(qū)號(hào)。
MultipleOutputs 的使用方式 的使用方式: :: :
想要使用 MultipeOutputs,需要完成以下四個(gè)步驟:
1. 在 Reducer 中聲明 MultipleOutputs 的變量
private MultipleOutputs
2. 在 Reducer 的 setup 函數(shù)中進(jìn)行 MultipleOutputs 的初始化
protected void setup(Context context)throws IOException, InterruptedException {
multipleOutputs = new MultipleOutputs
}
3. 在 reduce 函數(shù)中進(jìn)行輸出控制
protected void reduce(Text key, Iterable values, Context context)throws IOException,
InterruptedException {
for (Text value : values) {
multipleOutputs.write(NullWritable.get(), value, key.toString());
}
}
4. 在 cleanup 函數(shù)中關(guān)閉輸出 MultipleOutputs
protected void cleanup(Context context)throws IOException, InterruptedException {
multipleOutputs.close();
}
注意:multipleOutputs.write(key, value, baseOutputPath)方法的第三個(gè)函數(shù)表明了該輸出所在的目錄(相對(duì)于用戶(hù)指定的輸出目錄)。如果baseOutputPath不包含文件分隔符“/”,那么輸出的文件格式為baseOutputPath-r-nnnnn(name-r-nnnnn);如果包含文件分隔符“/”,例如baseOutputPath=“029070-99999/1901/part”,那么輸出文件則為