Creating objects via txt file into an array in Java

ぐ巨炮叔叔 提交于 2019-12-31 03:56:39

问题


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 (exemples data.txt) :

  • Sedane
  • 2005
  • 195000
  • Diesel
  • Blue
  • SUV
  • 2013
  • 34000
  • Fuel
  • Black

Each object is made true a class that i've build called Cars. So the 1 line is the type of car, the 2nd the year of built, the 3rd line is the milage, the 4th is the type of fuel, and the 5th line is the color of the car.

So basicly i need to open the file, and load the data into the memory when i execute my program into an array with object in it.

I'm ok to open the file but i'm blocked when it comes to reading the data and putting it in an array.

The array size is 2 for this exemple, but if i have more entries in the file it's going to adapt it's size when loading at the startup of the program.

Here's what i've got unti now (for my code ...)

public static void loadCars () {
    FileReader fopen;
    BufferedReader opened;
    String line;

    try {
        fEntree = new FileReader( "data.txt" );
        opened = new BufferedReader( fopen );
        while ( opened.ready() ) {
            line = opened.readLine();
            // Don't know what to do here ????
        }
        opened.close();
    } catch ( IOException e ) {
        System.out.println( "File doesn't exist !" );
    }

}

回答1:


LineNumberReader  lnr = new LineNumberReader(new FileReader(new File("File1")));
lnr.skip(Long.MAX_VALUE);

long length = lnr.getLineNumber();

lnr.close();

in = new BufferedReader(new FileReader( "data.txt" ));

Car[] cars= new Car[length/5];
String currentLine;
int i=0;

for(int i=0;i<length/5;i+=5) {
    String name = in.readLine();
    String year = in.readLine();
    String miles = in.readLine();
    String gas = in.readLine();
    String color = in.readLine();
    cars[i] = new Car(name,year,miles,gas,color);
}

You'll have to handle exceptions too, surround stuff in try catch structures.




回答2:


Someting like this will do the trick. I'm adding the file contents line by line to an Arraylist instead of an array though. This way you don't have to know how big your array needs to be before hand. Plus you can always change it to an array later.

public ArrayList<String> readFileToMemory(String filepath)
{
    in = new BufferedReader(new FileReader( "data.txt" ));
    String currentLine = null;
    ArrayList<String> fileContents = new ArrayList<String>();

    try
    {
        while((currentLine = in.readLine()) != null)
        {
            fileContents.add(currentLine);
        }
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        try
        {
            in.close();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }

    return fileContents;
}



回答3:


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<Car> carList = new ArrayList<Car>();
    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.



来源:https://stackoverflow.com/questions/23145416/creating-objects-via-txt-file-into-an-array-in-java

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