ArrayIndexOutofBounds在csv MapReduce中读取空单元格时

时间:2017-04-14 00:52:09

标签: hadoop mapreduce hdfs

我正在尝试为以下数据运行MapReduce程序。

enter image description here

这是我的映射器代码:

@Override
protected void map(Object key, Text value, Mapper.Context context) throws IOException, ArrayIndexOutOfBoundsException,InterruptedException {
    String tokens[]=value.toString().split(",");
    if(tokens[6]!=null){
        context.write(new Text(tokens[6]), new IntWritable(1));
    }

}

由于我的一些单元格数据为空,当我尝试读取Carrier_delay列时,我收到以下错误。请指教。

17/04/13 20:45:29 INFO mapreduce.Job: Task Id : attempt_1491849620104_0017_m_000000_0, Status : FAILED
Error: java.lang.ArrayIndexOutOfBoundsException: 6
    at Test.TestMapper.map(TestMapper.java:22)
    at Test.TestMapper.map(TestMapper.java:17)
    at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:764)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:340)
    at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)

enter image description here

Configuration conf = new Configuration();
Job job = Job.getInstance(conf,"IP Access");
job.setJarByClass(Test.class);
job.setMapperClass(TestMapper.class);

job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(IntWritable.class);

job.setReducerClass(TestReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);

FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);

3 个答案:

答案 0 :(得分:0)

所有列都是图片中显示的列?如果是这种情况,记住java数组是0索引的,你的列的范围是0到5,所以标记[6]它超出界限。或者根据您的必要逻辑,您还可以在if:

中添加验证
  

if(tokens.length> n&& tokens [n]!= null){           context.write(new Text(tokens [n]),new IntWritable(1));           }

答案 1 :(得分:0)

运营商延迟是第二个字段,因此您需要使用令牌[1]进行访问,因为数组索引从0开始。您还可以在访问特定索引之前进行长度检查。 Token [6]给出错误,因为你有6列。如果你正在访问最后一个字段,它将是Token [5] I.e length减去1。

答案 2 :(得分:0)

问题在于:if(tokens[6]!=null){

问题是你想获取标记[6]的值,然后检查它是否为空。但是,有些行只包含六列(第七列是空的),因此在这些情况下,tokens是一个六元素数组。这意味着它包含从tokens[0]tokens[5]的值。当您尝试访问tokens[6]时,超出了数组的大小,因此您得到一个ArrayIndexOutOfBoundsException。

正确的做法是:

IntWritable one = new IntWritable(1); //this saves some time ;)
Text keyOutput = new Text(); //the same goes here

@Override
protected void map(Object key, Text value, Mapper.Context context) throws IOException, ArrayIndexOutOfBoundsException,InterruptedException {
    String tokens[]=value.toString().split(",");
    if(tokens.length == 7){
        keyOutput.set(tokens[6]);
        context.write(keyOutput, one);
    }

}

更多提示:根据您的部分代码判断,我想您要计算特定载波延迟值出现的次数。在这种情况下,您也可以使用组合器来加速该过程,就像WordCount程序一样。您还可以将载波延迟解析为IntWritable,以节省时间和空间。

相关问题