Silent15
Silent15

Reputation: 11

Reading a text file into multiple arrays in Java

I'm currently working on a program that reads in a preset text file and then manipulates the data in various ways. I've got the data manipulation to work with some dummy data but I still need to get the text file read in correctly.

The test file looks like this for 120 lines:

Aberdeen,Scotland,57,9,N,2,9,W,5:00,p.m. Adelaide,Australia,34,55,S,138,36,E,2:30,a.m. Algiers,Algeria,36,50,N,3,0,E,6:00,p.m.(etc etc)

So each of these needs to be read into its own array, in order String[] CityName,String[] Country,int[] LatDeg,int[] LatMin,String[] NorthSouth,int[] LongDeg,int LongMin,String[] EastWest,int[] Time.String[] AMPM

So the problem is that while I'm reasonably comfortable with buffered readers, designing this particular function has proven difficult. In fact, I've been drawing a blank for the past few hours. It seems like it would need multiple loops and counters but I can't figure out the precisely how.

Upvotes: 0

Views: 2868

Answers (3)

DevilsHnd - 退した
DevilsHnd - 退した

Reputation: 9192

To carry out this task I should think the first thing you want to do is establish how many lines of data actually exist within the data file. You say it is 120 lines but what if it happens that it will be more or less? We would want to know exactly what it is so as to properly initialize all our different Arrays. We can use a simple method to accomplish this, let's call it the getFileLinesCount() method which will ulitmately return a Integer value that would be the number of text lines the data file holds:

private int getFileLinesCount(final String filePath) {
    int lines = 0;
    try{
        File file =new File(filePath);
        if(file.exists()){
            FileReader fr = new FileReader(file);
            try (LineNumberReader lnr = new LineNumberReader(fr)) {
                while (lnr.readLine() != null){ lines++; }
            }
        }
        else { 
            throw new IllegalArgumentException("GetFileLinesCount() Method Error!\n"
                    + "The supplied file path does not exist!\n(" + filePath + ")");
        }
    }
    catch(IOException e){ e.printStackTrace(); }
    return lines;
}

Place this method somewhere within your main class. Now you need to Declare and initialize all your Arrays:

String filePath = "C:\\My Files\\MyDataFile.txt";
int lines = getFileLinesCount(filePath);
String[] CityName = new String[lines];
String[] Country = new String[lines];
int[] LatDeg = new int[lines];
int[] LatMin = new int[lines];
String[] NorthSouth = new String[lines];
int[] LongDeg = new int[lines];
int[] LongMin = new int[lines];
String[] EastWest = new String[lines];
int[] Time = new int[lines];
String[] AMPM = new String[lines];

Now to fill up all those Arrays:

public static void main(String args[]) {
    loadUpArrays();

    // Do whatever you want to do 
    // with all those Arrays.....
}

private void loadUpArrays() {
    // Read in the data file.
    try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
        String sCurrentLine;
        int x = 0;

        // Read in one line at a time and Fill the Arrays...
        while ((sCurrentLine = br.readLine()) != null) {
             // Split each line read into an array upon itself.
    String[] fileLine = sCurrentLine.split(",");

             // Fill our required Arrays...
             CityName[x] = fileLine[0];
             Country[x] = fileLine[1];
             LatDeg[x] = Integer.parseInt(fileLine[2]);
             LatMin[x] = Integer.parseInt(fileLine[3]);
             NorthSouth[x] = fileLine[4];
             LongDeg[x] = Integer.parseInt(fileLine[5]);
             LongMin[x] = Integer.parseInt(fileLine[6]);
             EastWest[x] = fileLine[7];
             Time[x] = Integer.parseInt(fileLine[8]);
             AMPM[x] = fileLine[9];
             x++;
        }
        br.close();
    } 
    catch (IOException ex) { ex.printStackTrace(); } 
}

Now, I haven't tested this, I just quickly punched it out but I think you can get the jest of it.

EDIT:

As @Mad Physicist has so graciously pointed out within his comment below, a List can be used to eliminate the need to count file lines therefore eliminating the need to read the data file twice. All the file lines can be placed into the List and the number of valid file lines can be determined by the size of the List. Filling of your desired arrays can now also be achieved by iterating through the List elements and processing the data accordingly. Everything can be achieved with a single method we'll call fillArrays(). Your Arrays declaration will be a little different however:

String[] CityName;
String[] Country;
int[] LatDeg;
int[] LatMin;
String[] NorthSouth;
int[] LongDeg;
int[] LongMin;
String[] EastWest;
String[] Time;
String[] AMPM;    

public static void main(String args[]) {
    fillArrays("C:\\My Files\\MyDataFile.txt");

    // Whatever you want to do with all 
    // those Arrays...
} 

private void fillArrays(final String filePath) {
    List<String> fileLinesList = new ArrayList<>();
    try{
        File file = new File(filePath);
        if(file.exists()){
            try (BufferedReader br = new BufferedReader(new FileReader(file))) {
                String strg;
                while((strg = br.readLine()) != null){
                    // Make sure there is no blank line. If not
                    // then add line to List.
                    if (!strg.equals("")) { fileLinesList.add(strg); }
                }
                br.close();
            }
        }
        else { 
            throw new IllegalArgumentException("GetFileLinesCount() Method Error!\n"
                    + "The supplied file path does not exist!\n(" + filePath + ")");
        }

        // Initialize all the Arrays...
        int lines = fileLinesList.size();
        CityName = new String[lines];
        Country = new String[lines];
        LatDeg = new int[lines];
        LatMin = new int[lines];
        NorthSouth = new String[lines];
        LongDeg = new int[lines];
        LongMin = new int[lines];
        EastWest = new String[lines];
        Time = new String[lines];
        AMPM = new String[lines];

        // Fill all the Arrays...
        for (int i = 0; i < fileLinesList.size(); i++) {
            String[] lineArray = fileLinesList.get(i).split(",");
            CityName[i] = lineArray[0];
            Country[i] = lineArray[1];
            LatDeg[i] = Integer.parseInt(lineArray[2]);
            LatMin[i] = Integer.parseInt(lineArray[3]);
            NorthSouth[i] = lineArray[4];
            LongDeg[i] = Integer.parseInt(lineArray[5]);
            LongMin[i] = Integer.parseInt(lineArray[6]);
            EastWest[i] = lineArray[7];
            Time[i] = lineArray[8];
            AMPM[i] = lineArray[9];
        }
    }
    catch(IOException e){ e.printStackTrace(); }
}  

On another note...your Time Array can not be Integer since in data, what is considered the time contains a colon (:) which is a alpha character therefore (in case you haven't noticed) I have changed its declaration to String[]

Upvotes: -1

VHS
VHS

Reputation: 10174

I am assuming that you have one city per line type of file structure. If it is not, it will require a bit of tweaking in the following solution:

I will do the following way if I am more comfortable with BufferReader as you say:

List<List<String>> addresses = new ArrayList<List<String>>();
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
    for(String line; (line = br.readLine()) != null; ) {
        addresses.add(line.split(","));
    }
}

Later, let's say you want to retrieve the country information of say 'Adelaid', you can try the following:

for (List<String> cityInfo : addresses) {
   if("Adelaid".equals(cityInfo.get(0)) {
      country = cityInfo.get(1);
   }
}

Upvotes: 2

Sriram Rajendran
Sriram Rajendran

Reputation: 56

Instead of creating different arrays (like String[] CityName,String[] Country, etc.,), try using a Domain Object.

Here, you can have a Domain object or Custom class Location with attributes

    public class Location
    {
    private String cityName;
    private String country;
    private String latDeg;
    etc

    getters();
    setters();
    }`

Then you can write a file reader, each line item in the file will be a Location. So result will have

    Location[] locations;

or List locations;`

Upvotes: 1

Related Questions