Java 如何填写地图?
在我的mapper.class中 和我的输入文件:Java 如何填写地图?,java,hadoop,mapper,Java,Hadoop,Mapper,在我的mapper.class中 和我的输入文件: public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); int left = line.indexOf("{"); int right = line.ind
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
int left = line.indexOf("{");
int right = line.indexOf("}");
String subMyString = line.substring(left+1, right);
for (String myWord : subMyString.split("\\W+")) {
if (myWord.length() > 0)
context.write(new Text(myWord), new IntWritable(1));
}
}
自然:line=…bla..bla..{asd assda sddsaasd asd}
所有行中都包含“{”和“}”字符。我想在这些字符之间填入上下文。但在编译过程中,我得到了java.lang.StringIndexOutOfBoundsException
我应该如何更改代码?为什么我会出错
谢谢。从您提供的代码中,有两种方法可以获得
java.lang.StringIndexOutOfBoundsException
{
和}
不平衡{
和}
的情况。因为,如果值中不存在这些变量,left
和right
变量将变为-1
。因此您会得到一个StringIndexOutOfBoundsException
...
...bla..bla..{asd assda sddsaasd asd}
...bla..bla..{asd assda sddsaasd asd}
...bla..bla..{asd assda sddsaasd asd}
...
也许不是每行都有
{
和}
?你为什么不做一个健全的检查,看看是左
还是右
=-1
?每行都有{和},用log测试。
//......
int left = line.indexOf("{");
int right = line.indexOf("}");
if(left > 0 && right > 0){
String subMyString = line.substring(left+1, right);
for (String myWord : subMyString.split("\\W+")) {
if (myWord.length() > 0)
context.write(new Text(myWord), new IntWritable(1));
}
}
//..........