【发布时间】:2018-12-06 06:09:23
【问题描述】:
我正在将值从制表符分隔的文本文件中提取到 groovy 中的列表中。但是我遇到了ArrayIndexOutOfBoundsException。
代码
println("Reading File Contents")
def fullArray = new String[31721][4]
def availableArray = new String[1386][2]
def filteredFullArray = new String[1386][5]
String fileContents = new File('beliefs.txt').text
String availableContents = new File('available.txt').text
def count = 0
fileContents.eachLine { line ->
String[] str
str = line.split('\t')
def subCount = 0
for (subCount; subCount < str.length; subCount++) {
fullArray[count][subCount] = str[subCount]
}
count++
}
beliefs.txt
1 Azerbaijan hasOfficialLanguage Azerbaijani_language
2 Augustus hasChild Julia_the_Elder
3 Arthur_Aikin isCitizenOf England
4 Arthur_Aikin diedIn London
5 Alexander_III_of_Russia isMarriedTo Maria_Feodorovna__Dagmar_of_Denmark_
6 Alexander_III_of_Russia hasChild Nicholas_II_of_Russia
7 Alexander_III_of_Russia hasChild Grand_Duke_Michael_Alexandrovich_of_Russia
8 Alexander_III_of_Russia hasChild Grand_Duchess_Olga_Alexandrovna_of_Russia
9 Alexander_III_of_Russia hasChild Grand_Duke_Alexander_Alexandrovich_of_Russia
10 Alexander_III_of_Russia hasChild Grand_Duke_George_Alexandrovich_of_Russia
...
...
...
31719 Minqi_Li isKnownFor Chinese_New_Left
31720 Henry_Bates_Grubb isKnownFor Mount_Hope_Estate
31721 Thomas_Kuhn isKnownFor Paradigm_shift
运行它会给我以下错误。
捕获:java.lang.ArrayIndexOutOfBoundsException:4 java.lang.ArrayIndexOutOfBoundsException:4 在 extractBeliefs$_run_closure1.doCall(extractBeliefs.groovy:19) 在 extractBeliefs.run(extractBeliefs.groovy:12)
我知道发生上述错误的原因。但由于我的数组没有超过最后一个索引,并且错误显示在fileContents.eachLine { line -> 行,所以我无法找到出错的地方。
在这方面的任何建议都将受到高度赞赏。
【问题讨论】:
-
你在一行上有一个额外的标签。
-
找到带有额外选项卡的行的一种方法是将文件以制表符分隔的形式导入 Excel,然后快速向下查看 E 列以查看文本的位置。
-
谢谢。但问题是,它大约有 23000 行,因此,我正在研究一种方法来自动连接当前以制表符分隔且故意不应该如此的任何文本。
-
您可以只增加
fullArray的第二个维度,这样它就足以存储在线上最多的字段。或者您可以将for循环中的条件更改为subCount < str.length && subCount < 4。
标签: java arrays groovy indexoutofboundsexception filecontentresult