java:从txt文件中提取点

时间:2013-10-15 18:33:19

标签: java extractor

假设我有一个名为“filename”的txt文件。内部数据如下,

N
12  39
34  23
12  22
5   7
7   10
11  8
  .
  .
  .

左列包含每个点的x值。右列包含每个点的y值。 N是随后的点数据。我需要提取所有Point数据并将其存储在数据结构(例如List)中。我有什么方法可以做到吗?

2 个答案:

答案 0 :(得分:2)

File file = new File(filepath);
BufferedReader br = new BufferedReader(file.getInputStream);
int n = Integer.parseInt(br.readLine());

for (int i = 0; i < n-1; i++) // reads n-1 points, if you have n points to read, use n instead of "n-1"
{
    line = br.readLine();
    StringTokenizer t = new StringTokenizer(line, " ");

    int x = Integer.parseInt(t.nextToken());
    int y = Integer.parseInt(t.nextToken());

    // do whatever with the points
}

这适用于像这样的输入文件,

3           // line 1 
1 2         // line 2
3 4         // line 3

答案 1 :(得分:1)

我的解决方案使用Scanner代替BufferedReader / StringTokenizer

Scanner scanner = new Scanner(new File("filename"));
int n = scanner.nextInt();

for (int i = 0; i < n; i++) {
    int x = scanner.nextInt();
    int y = scanner.nextInt();

    // do something with the point or store it
}

它可能没有那么快,但它更容易阅读和写作。