Warm tip: This article is reproduced from stackoverflow.com, please click
csv java separator

How use 2 char as separator on CSVreader

发布于 2020-03-27 10:32:19

I want people to upload CSV in my database, but some use , as separator/delimiter and some use ;.

Is there a simple solution for this?

CSVReader csvReader = new CSVReader(new InputStreamReader(inputStream), ';', '"', 1);
Questioner
Thiago Mohr da Silveira
Viewed
51
163k 2019-07-04 09:57

If you're expecting people to send you files, you should require them to use the format you decided, and warn them any other format will be ignored. And make sure you process invalid formats correctly by gracefully reporting an error instead of crashing...

I suggest you redirect your users to the appropriate RFC 4180, in case they want to be fully compliant with the CSV standard.

If you're nice, you can add an option for them to enter the separator they used when they upload the file (and make sure you handle cases when they mistyped it or willfully gave the wrong one).

If you're even nicer, you can read the first line and try different commonly used separators (<space>, \t, ,, ;, ...) and choose the one that gives you the biggest number of tokens.

Whenever you're dealing with user input, you'll have to put a lot of effort (and code) validating every corner-case.