Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if the file is a CSV file?

I have a scenario wherein the user uploads a file to the system. The only file that the system understands in a CSV, but the user can upload any type of file eg: jpeg, doc, html. I need to throw an exception if the user uploads anything other than CSV file.

Can anybody let me know how can I find if the uploaded file is a CSV file or not?

like image 682
Mithun Avatar asked Jun 18 '10 09:06

Mithun


2 Answers

CSV files vary a lot, and they all could be called, legitimately, CSV files.

I guess your approach is not the best one, the correct approach would be to tell if the uploaded file is a text file the application can parse instead of it it's a CSV or not.

You would report errors whenever you can't parse the file, be it a JPG, MP3 or CSV in a format you cannot parse.

To do that, I would try to find a library to parse various CSV file formats, else you have a long road ahead writing code to parse many possible types of CSV files (or restricting the application's flexibility by supporting few CSV formats.)

One such library for Java is opencsv

like image 177
Vinko Vrsalovic Avatar answered Oct 05 '22 01:10

Vinko Vrsalovic


If you're using some library CSV parser, all you would have to do is catch any errors it throws.

If the CSV parser you're using is remotely robust, it will throw some useful errors in the event that it doesn't understand the file format.

like image 34
Jamie Wong Avatar answered Oct 05 '22 01:10

Jamie Wong