简体   繁体   中英

How to convert a monolithic CSV String into a List<String>?

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?

I think it should be as simple as:

String allData /* = readCSVFromFile() */;
String[] rows = allData.split("\r\n");
List<String> rowList = Arrays.asList(rows);

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM