如何将此文本文件读入以下类数组?

时间:2016-05-28 17:14:30

标签: java

我有一个班级学生和两个孩子班,CasualStudent和PermanentStudent。我现在正在这样做。

Employee[] a = new Employee[10];
int count;
a[0] = new PermanentStudent("John", "LUI", "HJFDDFDFJ"); 
a[1] = new PermanentStudent("Peter", "VAMPLEW", "VAM12345678");
a[2] = new PermanentStudent("Rudi", "SKACEL", "SKA51515151");
a[3] = new CasualStudent("Katie","BLACKBURN","BLA41925612");
a[4] = new CasualStudent("Neal","STEPHENSON","STE97527467");
a[5] = new CasualStudent("Neneh","CHERRY","CHE98765432");
a[6] = new CasualStudent("Chris","BROOKMYRE","BRO97635198");
a[7] = new CasualStudent("Grace","HOPPER","HOP26554432");
a[8] = new CasualStudent("Randall","MUNROE","XKCD1234567");
a[9] = new CasualStudent("Kaylee","FRYE","FRY90224718");

这些子类中的每一个都有一个构造函数,我手动编码了代码中的数据。现在,我想从.txt文件中读取这些数据。我知道怎么读,直到现在我都这样做了:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Program {
    public static void main(String[] args) {

    BufferedReader reader = new BufferedReader(new FileReader(
        "file.txt"));
    while (true) {
        String line = reader.readLine();
        if (line == null) {
        break;
        }
        System.out.println(line);
    }
    reader.close();
    }
}

但是如何将数据读入这样的类?我是Java的新手,我无法理解如何做到这一点?请指导我正确的方向。谢谢!

此外,文本文件将始终包含10行,每行将具有以下格式。

John LUI HJFDDFDFJ
..................

代码:

61. int i = 0;
62. for (i = 0; i < 10; i++)
63. {
64.     String x = a[i].toString();
65.     System.out.println(x);
66. }

1 个答案:

答案 0 :(得分:6)

最简单的方法如下:

Employee[] employees = new Employee[10];
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {

  for (int i = 0; i < 3; i++) {
    String line = reader.readLine();
    String[] parts = line.split(" ");
    employees[i] = new PermanentStudent(parts[0], parts[1], parts[2])
  }

  for (int i = 3; i < 10; i++) {
    String line = reader.readLine();
    String[] parts = line.split(" ");
    employees[i] = new CasualStudent(parts[0], parts[1], parts[2])
  }
}