简体   繁体   中英

CSV parsing in Java: how do I split this token?

I've got string in my CSV file uploaded on server in the form of:

21-June-2012 Football MU-Chelsea London (first row)
22-June-2012 Basketball NY-MY New York (second row)

When I do CSV parsing with the code below:

BufferedInputStream bis = new BufferedInputStream(stream);
ByteArrayBuffer baf = new ByteArrayBuffer (50);int current = 0;
int current = 0;
while ((current = bis.read()) != -1){
    baf.append((byte)current);
}
String stockTxt =  new String (baf.toByteArray());  
String [] tokens = stockTxt.split(",");
String date_CSV     = tokens [2];
String time_CSV     = tokens [3];
String game_CSV     = tokens [4];
String gamedesc_CSV = tokens [5];
String venue_CSV    = tokens [6];

It shows the result:

token [0] = 21-June-2012 
token [1] = Football 
token [2] = MU-Chelsea 
token [3] = London 22-June-2012 
token [4] = Basketball 
token [5] = NY-MY
token [6] = New York

For the token [3] my expected reslt is London and my expected result for token 4 is 22-June-2012 . How do I do the splitting for this?

每行都是一行,因此您需要先逐行阅读输入并将其拆分。

Since you know that the data is in “Excel CSV format” you should search for a library that can handle this format. There are several which you can use for free. After that, reading the file gets very simple, since you don't need to be concerned about the file format anymore. Your code should only be concerned about readLine and readField , not about handling the IO stuff itself.

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