0

I have a CSV stored in a String:

Abc, Def, Ghi, Jkl, Mno[CR|LF]
Abc, Def, Ghi, Jkl, Mno[CR|LF]
Abc, Def, Ghi, Jkl, Mno[CR|LF]
Abc, Def, Ghi, Jkl, Mno[CR|LF]

When I open the file in Notepad++ and use "Show All Characters" I see the newline character at the end of each line represented by the [CR|LF] notation I indicated above.

How do convert this monolithic String into a List<String> where each line above represents a separate String in the List but without the [CR|LF] characters?

Rob
  • 1

2 Answers2

2

I think it should be as simple as:

String allData /* = readCSVFromFile() */;
String[] rows = allData.split("\r\n");
List<String> rowList = Arrays.asList(rows);
Mark Peters
  • 80,126
  • 17
  • 159
  • 190
  • Just a note, my answer assumes that `[CR|LF]` means always CR followed by LF. If that's not the case and it could instead contain either or both, you could use a more complex regex like `.split("[\r|\n]+")` – Mark Peters Jul 04 '11 at 18:48
1

Use a BufferedReader. Something like this:

List<String> rows = new ArrayList<String>();
BufferedReader r = new BufferedReader(new FileReader("file.csv"));
String line = null;
while ((line = r.readLine()) != null)
{
    rows.add(line);
}
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287