Scanning text file into array of objects

爷,独闯天下 提交于 2019-12-10 22:40:00

问题


I have a comma separated text file with information in the format:

firstname,lastname,meal1,meal2,meal3,meal4 ....with each new student on a new line.

I have the following student object.

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

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

I need a method that is to be used from another class to populate an Array of student objects.

I am unsure how to do this with the Scanner as I only need the first two from each line, any help pointing me in the right direction would be very thankful.

~Thanks!


回答1:


  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();
    }



回答2:


As a tip I can post you the code how to read lines from file with scanner. Then you can parse a line. Try to do this by yourself. Good luck.

    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();
    }


来源:https://stackoverflow.com/questions/19023906/scanning-text-file-into-array-of-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!