Search code examples
javacsvpattern-matchingstring-parsing

Parsing file and detection of pattern in Java


My problem is quite simple, i am parsing a CSV file, line after line and i want to get the values of the columns. The separators used are simply ";", but my file can have quite a lot of columns, and they won't be always in the same order.

So as example for my .CSV file :

time;columnA;columnB,ColumnC
27-08-2013 14:43:00; this is a text; this too; same here

And i would like to be able to get all the values of time, columnA, columnB and columnC. What would be the easiest way?

I used StringUtils.countMatches(input, ";"); to get the number of separators i have. I started trying to make a String index[][] = {{"time", "columnA", "columnB", "columnC"}{}}; And my plan was to fill this with the number of ";" before each other variable, so that i could easily now which result stands for which variable.

But now i'm quite stuck...

If you want me to show more of my code, i can. Hope that someone can help me ! :)

(sorry for the poor english).


Solution

  • You can simply use split() method

    For instance:

    Scanner aScanner = ...
    ArrayList<String> L = new ArrayList<String>();
    while(aScanner.hasNextLine()){
        L.add(aScanner.nextLine());
    }
    int rows = L.size();
    String[][] S = new String[rows][];
    for (int i = 0; i < rows; i++) {
        S[i] = L.get(i).split(";");
    }