我有一个用制表符分隔的文本文档。每一行都有相同类型的重复信息。当我使用hasNextLine()和一个计数器对行进行计数时,它只对一部分行进行计数。我仍然可以创建我得到的计数器大小的数组。当我使用for循环来填充数组时,结果是意想不到的。
以下是我所做工作的总结。
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args) {
try {
Scanner input = new Scanner(new File("input.txt"));
int lines = 0;
input.nextLine(); //for the header of the table
while(input.hasNextLine()) {
lines++;
input.nextLine();
}
System.out.println(lines);//here I don't get the total amount
String[] colors = new String[lines];
int[] number = new int[lines];
fillArray(colors, number);
System.out.println(colors[i] + i);
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void fillArray(String[] color, int[] numbers) {
try {
Scanner input = new Scanner(new File("input.txt"));
input.nextLine(); //for table header
input.useDelimiter("\\t");
for(int i = 0; i < color.length; i++) {
color[i] = input.next();
input.next(); //info i'm not using
numbers[i] = input.nextInt();
input.nextLine(); //consumes '\n'
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
它会编译,但我的结果如下所示:
null\n yellow0\n null1\n null2\n null3\n等等。
它还显示了正确的颜色和数字;但仅显示一行。
任何帮助都将不胜感激。我不经常使用useDelimiter,但据我所知,它将使'\t‘分隔标记,而不是空格和'\n’
发布于 2014-03-19 08:09:17
不要担心,使用它:
final List<String> lines = Files.readAllLines(Paths.get("input.txt"),
StandardCharsets.UTF_8);
然后,读取的行数就像lines.size()
一样简单,您只需遍历列表来处理您的行数。
发布于 2014-03-19 08:12:55
您可以使用OpenCSV http://opencsv.sourceforge.net/#custom-sepators。使用它实现CSV Reader程序真的很容易。
https://stackoverflow.com/questions/22493668
复制相似问题