1

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 !" );
    }

}
Cyberflow
  • 1,255
  • 5
  • 14
  • 24

3 Answers3

1

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;
}
j.jerrod.taylor
  • 1,120
  • 1
  • 13
  • 33
0
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.

Anubian Noob
  • 13,426
  • 6
  • 53
  • 75
  • Hi there Anubian Noob, Ty for replying. Each spot on the array is an object... lets say Cars [] arrayCars = new Cars [???]; – Cyberflow Apr 18 '14 at 00:08
  • @Cyberflow Welcome to StackOverflow! Don't post unconstructive comments like that. Instead post constructive criticism. Does this answer your question? Do you have any follow up questions? – Anubian Noob Apr 18 '14 at 00:11
  • How do i check to see how many lines to set how many spots i've got to create on the array ? – Cyberflow Apr 18 '14 at 00:11
  • Oh sorry, I didn't read part of your question, editing. Are ArrayLists ok or do you have to use arrays? – Anubian Noob Apr 18 '14 at 00:11
  • Try this: http://stackoverflow.com/questions/453018/number-of-lines-in-a-file-in-java – Anubian Noob Apr 18 '14 at 00:12
  • Hi there Anubian, trying your solution right now. My constructor has 2 INT native variable for Model (Sedan=0, SUV=1, etc.. and color). The string Sedan is stored into another array that same thing for colors. But my object contains it's number of position in the array. How could i get the info of the string out of the array table ? – Cyberflow Apr 18 '14 at 19:04
0

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.

WoDoSc
  • 2,598
  • 1
  • 13
  • 26
  • Hi Nicolas, your answer is really close to what i'm was thinking on doing ... but i need to create an Array with the number of car in the txt files (Quantity known by using modulo 5 like you did in the if) And yes there's INT type for the year, mileage – Cyberflow Apr 18 '14 at 00:36
  • if you adopt my solution you can create the array by doing: Car[] carArray=carList.toArray(new Car[carList.size()]); at the end of my code – WoDoSc Apr 18 '14 at 00:58