0

I am trying to get the values from the second last row and third column in a semicolon separated file. I can't seat to get the values from the second last row and the third column.

I have searched for a method to achieve this but it has been fruitless. I would greatly appreciate if someone could point me in the right direction with an example.

This is the code I have so far:

private static void readmyfile() throws IOException {

    String csvFilename = "C:/test.csv";

    CSVReader reader = new CSVReader(new FileReader(csvFilename), ';', '\'', 1);
    String[] nextLine;

    int rowNumber=-1;

    nextLine=reader.readNext();
    while (nextLine!=null){
        rowNumber++;
        String speed = nextLine[rowNumber];
        System.out.println(speed);
        nextLine=reader.readNext();
    }
}

My file is formatted like this:

Number; ID; NUM; Counter; Time
1;CCF;9999;1;18:07:05
1;CC8;8888;1;18:07:15
1;CC1;8888;1;18:07:15
1;DC7;1111;1;18:07:15
Date:;01/01/2000; Read:;5; on:;01.05; off:;02.04
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
user
  • 158
  • 6
  • 19

1 Answers1

1

Although you are reading the 2nd last line, this could possibly change to the 3rd or 4th last lines. Doing a custom solution here would definitely prove brittle. Therefore using a circular buffer such as Apache's CircularFifoBuffer will allow lines to be added without having to maintain a position count:

CSVReader reader = new CSVReader(new FileReader(csvFilename), ';', '\'', 1);

int rowCount = 2;                                    // save last 2 lines
Buffer<String[]> savedBuffer = new CircularFifoBuffer<String[]>(rowCount); 
String[] nextLine;
while ((nextLine = reader.readNext()) != null) {
   savedBuffer.add(nextLine);
}

int columnIndex = 2; // zero based
System.out.println(savedBuffer.get()[columnIndex]);

Note: You will need the Generics version of Commons-Collections for this example.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • Thank you for replying but the csv actually has thousands of rows I just posted a fragment. Ideally I will have the csv clear itself regularly but that is a job for another day. – user May 05 '13 at 20:48
  • I think a circular buffer is the best/most robust approach here. See update – Reimeus May 05 '13 at 22:14
  • It works a charm. I do have one question, where do I specify the column number and row number. I have never used this package before. – user May 06 '13 at 00:05
  • Set the size of the `CircularFifoBuffer` to accommodate the the last _n_ rows. The column index is as shown in the update. – Reimeus May 06 '13 at 00:16