Creating objects via txt file into an array in Java

后端 未结 3 1887
余生分开走
余生分开走 2021-01-24 21:23

I am trying to complete a little program.

I\'ve got a text file (.txt) to store different data on objects that i\'ve got.

The structure of the file is the next (

3条回答
  •  日久生厌
    2021-01-24 21:53

    You can look at my solution here below (I also corrected/simplified some problems with the variables for reading the file, anyway this was not the main topic):

    public static void loadCars() {
        FileReader fopen;
        BufferedReader opened;
        String line;
    
        ArrayList carList = new ArrayList();
        try {
            fopen = new FileReader("data.txt");
            opened = new BufferedReader(fopen);
    
            int nFields = 5; // we have 5 fields in the Car class
            String[] fields = new String[nFields]; // to temporary store fields values read line by line
            int lineCounter = 0;
            while ((line = opened.readLine()) != null) {
                fields[lineCounter] = line;
                lineCounter++;
                if ((lineCounter) % nFields == 0) { //it means we have all 5 fields values for a car
                    carList.add(new Car(fields)); //therefore we create a new car and we add it to the list of cars
                }
    
            }
            opened.close();
        } catch (IOException e) {
            System.out.println("File doesn't exist !");
        }
    }
    

    Basically we use an ArrayList to store all the cars, and we read the file, waiting to have all the fields values in order to create the Car object. I store the fields values in an array of Strings: I don't know how you implemented the Car class, but maybe it is useful to create a constructor that takes as parameter an array of strings, so it can set the fields, for instance:

    class Car {
    
        private String type;
        private String year;
        private String milage;
        private String fuel;
        private String color;
    
        public Car(String[] fields) {
            type=fields[0];
            year=fields[0];
            milage=fields[0];
            fuel=fields[0];
            type=fields[0];
        }
    }
    

    But I've to say that probably this is a little 'too static'. For simplicity I assumed that all your fields are of String type, but probably fields like 'year' or 'milage' might be of int type. In this case you can use array of Object[] (instead of String[]), and then cast the value with the right type.

    I hope this may help you.

提交回复
热议问题