5

I have managed to split a CSV file based on the commas. I did this by placing a dummy String where ever there was a ',' and then splitting based on the dummy String.

However, the CSV file contains things such as:

something, something, something
something, something, something

Therefore, where there is a new line, the last and first values of each line get merged into their own string. How can I solve this? I've tried placing my dummy string where \n is found to split it based on that but to no success.

Help?!

1
  • Why didn't you split directly using commas? Anyway, post a sscce.org to get better help. Commented Feb 2, 2012 at 11:59

4 Answers 4

6

I would strongly recommend you not reinventing the wheel :). Go with one of the already available libraries for handling CSV files, eg: OpenCSV

Sign up to request clarification or add additional context in comments.

Comments

5

I don't see why you need a dummy string. Why not split on comma?

BufferedReader in = new BufferedReader(new FileReader("file.csv"));
String line;
while ((line = in.readLine()) != null) {
    String[] fields = line.split(",");
}

2 Comments

This doesn't help me split based on lines. That was the question.
you're supposed to read each line and split each one separately. Then you wouldn't have the problem of lines merging.
1

As per the dummy strings you mentioned, it could be easily processed with the help of an existing library. I would like to recommand the open source library uniVocity-parsers, which procides simplfied API, significent performance and flexibility.

Just refer to few lines of code to read csv data into memory with array:

private static void parseCSV() throws FileNotFoundException {
    CsvParser parser = new CsvParser(new CsvParserSettings());
    List<String[]> parsedData = parser.parseAll(new FileReader("/examples/example.csv"));

    for (String[] row : parsedData) {
        StringBuilder strBuilder = new StringBuilder();
        for (String col : row) {
            strBuilder.append(col).append("\t");
        }
        System.out.println(strBuilder);
    }
}

Comments

-1

use the followin it will split lines

               String[] a=scanner.next().split(" ");

Comments

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.