MapReduce java.lang. ArrayIndexOutOfBoundsException.ArrayIndexOutOfBoundsException: 0

#java #mapreduce

#java #mapreduce

Вопрос:

Я пытаюсь запустить mapreduce на java, но получаю эту ошибку.

 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
        at com.mapreduce.WordCount.run(WordCount.java:23)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:70)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:84)
        at com.mapreduce.WordCount.main(WordCount.java:18)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:498)
        at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
  

WordCount.java

 package com.mapreduce;

import java.io.IOException;
import java.util.*;

import org.apache.hadoop.conf.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.conf.*;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.*;
import org.apache.hadoop.mapreduce.lib.output.*;
import org.apache.hadoop.util.*;

public class WordCount extends Configured implements Tool {

    public static void main(String args[]) throws Exception {
        int res = ToolRunner.run(new WordCount(), args);
        System.exit(res);
    }

    public int run(String[] args) throws Exception {
        Path inputPath = new Path(args[0]);
        Path outputPath = new Path(args[1]);

        Configuration conf = getConf();
        Job job = new Job(conf, this.getClass().toString());

        FileInputFormat.setInputPaths(job, inputPath);
        FileOutputFormat.setOutputPath(job, outputPath);

        job.setJobName("WordCount");
        job.setJarByClass(WordCount.class);
        job.setInputFormatClass(TextInputFormat.class);
        job.setOutputFormatClass(TextOutputFormat.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        job.setMapperClass(Map.class);
        job.setCombinerClass(Reduce.class);
        job.setReducerClass(Reduce.class);

        return job.waitForCompletion(true) ? 0 : 1;
    }

    public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
        private final static IntWritable one = new IntWritable(1);
        private Text word = new Text();

        @Override
        public void map(LongWritable key, Text value,
                        Mapper.Context context) throws IOException, InterruptedException {
            String line = value.toString();
            StringTokenizer tokenizer = new StringTokenizer(line);
            while (tokenizer.hasMoreTokens()) {
                word.set(tokenizer.nextToken());
                context.write(word, one);
            }
        }
    }

    public static class Reduce extends Reducer<Text, IntWritable, Text, IntWritable> {

        @Override
        public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable value : values) {
                sum  = value.get();
            }

            context.write(key, new IntWritable(sum));
        }
    }

}
  

Я понимаю, что это означает, что в массиве нет элементов, но что мне нужно сделать, чтобы запустить его? Я использую Maven для импорта всех необходимых библиотек. Я запускаю его в Windows. Код является примером из http://www.macalester.edu /~shoop/sc13/hadoop/html/hadoop/wc-detail.html

Комментарии:

1. Исключение ArrayIndexOutOfBoundsException предполагает, что args[] пуст.

2. ArrayIndexOutOfBoundsException, да, это довольно самоочевидно. Вы не получаете ожидаемые аргументы.

3. Я бы посоветовал вам сначала начать с книги по Java, а затем перейти к hadoop. Так будет проще, чем изучать Java через Hadoop.

Ответ №1:

Вам необходимо запустить вашу программу с аргументами, соответствующими пути ввода и пути вывода, поэтому ваша команда запуска должна иметь следующий формат:

 java -cp <my-classpath-here> com.mapreduce.WordCount <input-path> <output-path>
  

Комментарии:

1. Что мне делать, если я использую Windows?

2. то, что я предлагаю в своем ответе, не зависит от ОС, поэтому оно будет работать и в ОС Windows, предполагая, что вы правильно указали путь к классу и допустимый путь ввода и вывода

3. Будет ли путь ввода и вывода в этом случае указывать на текстовый документ?

4. путь ввода да, это должен быть путь к текстовому документу, путь вывода должен быть путем к файлу, который будет содержать результат вашей карты / сокращения

5. Должен ли my-classpath-here быть файлом jar?