我有一个制表符分隔的文件,我必须从文件中读取数据。
Col1 Col2 Col3
data1 data2 data3
data1 data2 data3
如果所有列都存在值,则没有问题。问题是有时少数列可能不包含如下值。
Col1 Col2 Col3
data1 data3
data1 data2
在上面的数据中,我能够读取第一行数据,因为 col2 的值为空字符串。 但是第二行的 col3 没有数据。在这里我得到数组索引越界异常。 为什么我没有得到第二行的 col3 的空字符串?
我使用的代码如下:
String dataFileName = "C:\\Documents and Settings\\User1\\some.txt";
/**
* Creating a buffered reader to read the file
*/
BufferedReader bReader = new BufferedReader(
new FileReader(dataFileName));
String line;
/**
* Looping the read block until all lines in the file are read.
*/
while ((line = bReader.readLine()) != null) {
/**
* Splitting the content of tabbed separated line
*/
String datavalue[] = line.split("\t");
String value1 = datavalue[0];
String value2 = datavalue[1];
String value3 = datavalue[2];
}
谢谢!
最佳答案
懒惰的方式是这样的:
...
String datavalue[] = Arrays.copyOf(line.split("\t"),3);
String value1 = datavalue[0];
String value2 = datavalue[1];
String value3 = datavalue[2];
...
基本上,您正在拆分内容并将其复制到一个新数组,其中填充的元素为 null,如记录的那样:
Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array. The resulting array is of exactly the same class as the original array.
关于java - 读取制表符分隔的文本文件时出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16079615/