将文本文件扫描到对象数组中

时间:2013-09-26 09:08:33

标签: java arrays class object java.util.scanner

我有一个逗号分隔的文本文件,其格式为:

firstname,lastname,meal1,meal2,meal3,meal4 ....每个新生都在新线上。

我有以下学生对象。

public class Student {
    private String first = null;
    private String last = null;

    public Student (String first, String last){
        this.first = first;
        this.last = last;
    }

我需要一个从另一个类中使用的方法来填充学生对象数组。

我不确定如何使用扫描仪完成此操作,因为我只需要每行的前两个,任何指示我正确方向的帮助都会非常感激。

〜谢谢!

2 个答案:

答案 0 :(得分:4)

  try {
        File file = new File("input.txt");
        Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {                
            String line = scanner.nextLine();
            String array[] = line.split(",");
            Student student  = new Student (array[0],array[1]);
            -------------------------
            -------------------------
            System.out.println("FirstName:"+ array[0]);
            System.out.println("LastName:"+ array[1]);
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

答案 1 :(得分:0)

作为提示,我可以向您发布如何使用扫描仪从文件中读取行的代码。然后你可以解析一行。尝试自己做。 祝你好运。

    Scanner s = null;
    try {
        s = new Scanner(new BufferedInputStream(new FileInputStream("Somefile.txt")));
        while (s.hasNextLine()){
            String line = s.nextLine(); //String line representation from file 
    } finally {
        if (s != null) s.close();
    }
相关问题