Search code examples
javacsvunivocity

Univocity Parsers: Calling a function from here is not working: parserSettings.selectFields( *some_function* );


I am using a .csv file and would like to pass a string constructed by a function to: parserSettings.selectFields( function );

During testing, when the string returned by the function is pasted directly into: parserSettings.selectFields( string ); the parsing works fine, however, when the function is used instead, the parse doesn't work, and there is only output of whitespace.

Here is the function:

    public String buildColList() {
            //Parse the qty col names string, which is a comma separated string
            String qtyString = getQtyString();
            List<String> qtyCols = Arrays.asList(qtyString.split("\\s*,\\s*"));

            String colString = StringUtils.join(qtyCols.toArray(), "\"" +  ", " + "\"");

            String fullColString;

            fullColString = "\"" + getString1() + "\""  + ", " + "\"" + getString2() + "\"" + ", " + "\"" + colString + "\"" + ", " + "\"" + getString4 + "\"";

            return fullColString;

        }

Here is how it is placed:

     parserSettings.selectFields(buildColList());

Any help would be greatly appreciated, thanks.


Solution

  • You need to return an array from your buildColList method, as the parserSettings.selectFields() method won't split a single string. Your current implementation is selecting a single, big header instead of multiple columns. Change your method to do something like this:

    public String[] buildColList() {
            //Parse the qty col names string, which is a comma separated string
            String qtyString = getQtyString();
            List<String> qtyCols = Arrays.asList(qtyString.split("\\s*,\\s*"));
    
            String colString = StringUtils.join(qtyCols.toArray(), "\"" +  ", " + "\"");
    
            String[] fullColString = new String[]{getString1(), getString2(), colString, getString4};
            return fullColString;
    }
    

    And it should work. You might need to adjust my solution to fit your particular scenario as I didn't run this code. Also, I'm not sure why you were appending quotes around the column names, so I removed them.

    Hope this helps.