在Mapreduce流程中,在Map端常常遇到需要根据来自不同数据源的<key,value>,进行不同的操作。因此,经常需要获取到<key,value>的数据来源。
获取文件名的大致流程为:Context(map函数里) → InputSplit → FileSplit → Path → String(file name)。
Context
Context是Mapper的内部类,在Map或Reduce任务中跟踪task的状态,Context在Map端执行时携带上下文信息。可理解为各函数执行时的桥梁,简单其作用与前后端服务交互的session相类似。
InputSplit
MapReduce的逻辑切片, InputSplit是Hadoop定义的用来传送给每个单独的map的数据,InputSplit存储的并非数据本身,而是一个分片长度和一个记录数据位置的数组。生成InputSplit的方法可以通过InputFormat()来设置。
FileSplit
FileSplit类继承于InputSplit,可获取目录名字 ,目录长度以及数据来源,简单使用如下:
import org.apache.hadoop.mapred.SplitLocationInfo;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import java.io.IOException;
public class FileSplitTest {
public static void main(String[] args) throws IOException {
FileSplit fs = new FileSplit();
String pathname=fs.getPath().getName();//获取目录名字
int depth = fs.getPath().depth(); //获取目录深度
fs.getClass();//获取当前类
long length = fs.getLength();//获取文件长度
SplitLocationInfo[] locationInfo =fs.getLocationInfo(); //获取位置信息
String[] locations = fs.getLocations(); //获取位置
}
}
可通过以下步骤获取数据源的目录名称,以及表名:
InputSplit inputSplit = context.getInputSplit();
//getParent()获取到路径
Path path = ((FileSplit) inputSplit).getPath().getParent();
String[] pathSplit = path.toString().split("/", -1);
1。 获得输入文件名 String input= context.getInputSplit(); context 就是 Context对象
2。获得输出路径 String outPutPath = context.getConfiguration().get("mapred.output.dir")