我有一个tsv txt文件,其中包含3行数据。
看起来像:
HG sn FA
PC 2 16:0
PI 1 18:0
PS 3 20:0
PE 2 24:0
26:0
16:1
18:2
我想将此文件读入Java中的二维数组。
但是无论我如何尝试,我始终会出错。
File file = new File("table.txt");
Scanner scanner = new Scanner(file);
final int maxLines = 100;
String[][] resultArray = new String[maxLines][];
int linesCounter = 0;
while (scanner.hasNextLine() && linesCounter < maxLines) {
resultArray[linesCounter] = scanner.nextLine().split("\t");
linesCounter++;
}
System.out.print(resultArray[1][1]);
我不断收到这个错误
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at exercise.exercise2.main(exercise2.java:31)
第31行是
System.out.print(resultArray[1][1]);
我找不到导致此错误不断出现的任何原因
在您的情况下,我将使用Java 7 Files.readAllLines
。
就像是:
String[][] resultArray;
List<String> lines = Files.readAllLines(Paths.get("table.txt"), StandardCharsets.UTF_8);
//lines.removeAll(Arrays.asList("", null)); // <- remove empty lines
resultArray = new String[lines.size()][];
for(int i =0; i<lines.size(); i++){
resultArray[i] = lines.get(i).split("\t"); //tab-separated
}
输出:
[[HG, sn FA ], [PC, 2, 16:0], [PI, 1, 18:0], [PS, 3, 20:0], [PE, 2, 24:0], [, , 26:0], [, , 16:1], [, , 18:2]]
这是文件(按下edit
并抓取内容,应将其制表符分隔):
HG sn FA
PC 2 16:0 PI 1 18:0 PS 3 20:0 PE 2 24:0 26:0 16:1 18:2
[编辑]
得到16:1
:
System.out.println(root[6][2]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句