Abiodun Adeoye
Abiodun Adeoye

Reputation: 1095

Problems with reading csv file with commas within its fields

Am having trouble reading a csv file with commas within its fields. it produces double quote when the csv is read and when this data is passed into a table the quotes rearranges the position of the values in different columns. I used the "|" to represent tables as a view but it is seperated with commas.

when it is open in with excel

  LD            |LA| L|       T            |A

 Car Park Store,|  |4a|South Bank Road     |

when it is opened with the codes

  LD            |LA| L|       T            |A

"Car Park Store |" |  |       4a           |South Bank Road

the idea is to make it appear the way it does in the excel.

   public void readFromFile(){
   List<String> output = new ArrayList<String>();
  try{
    BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
    String line = "";

    while ((line = bufferedReader.readLine()) != null){
     output.add(line);
    }

    bufferedReader.close();

  } catch(FileNotFoundException fne){
    csvReaderErrorMessage +=  "File '" + filename + "' cannot be found.";

  }catch(IOException ioe){
    csvReaderErrorMessage +=  "Problem reading file: '" + filename+"'";
  }

  csvDataModel.setData(output);

 }

Upvotes: 1

Views: 1956

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503090

The code you've given doesn't really parse the file at all. It splits it into lines, but that's all it does.

You should parse the lines into values - and fortunately, you don't need to write much code to do that yourself. Libraries like JavaCSV, OpenCSV and Super CSV make this easy.

So, after parsing you'll have a collection of rows, each of which will be a collection of values. You may want to create a class to handle each row, so that you can work with the data more cleanly. You should be able to format that nicely in your Swing UI without displaying things like "|" between values.

It's important to work with data in as appropriate a form as possible - so when you read a file, do all the parsing work as early as you can (unless you have a really good reason not to, of course) - that way the rest of your code can be much cleaner. Your UI code shouldn't care at all that you happened to load the data from a CSV file to start with.

Upvotes: 7

Related Questions