这是我的代码。该程序从我正在设置的文件中搜索特定片段
class z{
public static void main(String [] args) throws IOException{
String fileName = "file.txt";
String text = "{";
String delimiter = "}";
Optional<String> result =
Files
.lines(Paths.get(fileName))
.filter(e -> e.contains(text))
.map(e -> {
int start = e.indexOf(text);
int end = e.indexOf(delimiter, start + text.length());
return e.substring(start, end);
})
.findFirst();
result.ifPresent(System.out::println);
}
}
此代码出现此类错误,请帮助理解为什么会发生这种情况,以及如何解决此问题:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(String.java:1967)
at z.lambda$main$1(z.java:27)
at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
at java.util.stream.ReferencePipeline$2$1.accept(ReferencePipeline.java:175)
at java.util.Spliterators$IteratorSpliterator.tryAdvance(Spliterators.java:1812)
at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:498)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:464)
at z.main(z.java:29)
答案 0 :(得分:2)
您的堆栈跟踪包含以下行:
java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1 在java.lang.String.substring(String.java:1967)
所以它substring
失败了。这可能是因为indexOf
的{{1}}返回-1,这是找不到时返回的值。
在您进行过滤以确保其中包含end
时,您不会过滤该文件包含text
。
答案 1 :(得分:0)