1

I have the following code to read from csv file in android. It works fine expect for the case when i have commas in my column values.

    File file = new File(IMPORT_ITEM_FILE.getPath());

    BufferedReader bufRdr = null;
    try {
        bufRdr = new BufferedReader(new FileReader(file));
    } catch (FileNotFoundException e) {

    }
    String line = null;

    try {
        while ((line = bufRdr.readLine()) != null) {

            String[] insertValues = line.split(",");


                string column1 = insertValues[1];

                string column2 = insertValues[2];
        }

        bufRdr.close();
    }

My csv row is like : name of user ,"some string, with commas","2740740, 2740608",,"some, string, with commas"

How can i escape the commas within column values to read the columns.

2 Answers 2

4

I suggest you use http://opencsv.sourceforge.net/ . it will handle everything for you if your CSV file source file is correctly formatted.

Example usage:

InputStream csvStream = getAssets().open(yourCSVFile);
        InputStreamReader csvStreamReader = new InputStreamReader(csvStream);
        CSVReader csvReader = new CSVReader(csvStreamReader);
        String[] line;

        while ((line = csvReader.readNext()) != null) {
                     String example = line[0]; // first item of your csv row
                  }
Sign up to request clarification or add additional context in comments.

1 Comment

OpenCsv solved the problem. I used the he following code CSVReader reader = new CSVReader(new FileReader("yourfile.csv")); String [] nextLine; while ((nextLine = reader.readNext()) != null) { // nextLine[] is an array of values from the line System.out.println(nextLine[0] + nextLine[1] + "etc..."); }
1

I'd suggest splitting using RegEx. You could use something like: \"(.*?)\",?

I don't have Java setup on the computer I use, but something like this should work. Can't guarantee it will compile though.

String myString = "\"name of user\",\"official address, city\",\"2740740, 2740608\",,\"address, city, state\""

Pattern myPattern = Pattern.compile("\"(.*?)\",?"); 
Matcher myMatcher = myPattern.matcher(myString); // myPattern to match against string
while (myMatcher.find())
{
    System.out.println(myMatcher.group(1));
}

2 Comments

Your code compiles successfully. But it gives me only the columns values contained in double quotes. All other columns are skipped
Ahh OK, I thought all your values were within quotations. It may still be possible with RegEx, but if the other solution worked then that's probably a better way to go :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.