0

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

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

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

4

2 回答 2

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
于 2013-10-15T18:38:10.750 回答
1

My solution using Scanner instead of 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
}

It's probably not as fast, but it's much easier to read and write.

于 2013-10-15T18:48:02.083 回答