import java.io.*;

import java.util.*;

import javax.swing.*;
import javax.swing.table.*;


public class Csv2TableModel {
    /**
     * Rudimentary quick and dirty demo code
     *
     * @param args (Not used)
     */
    public static void main(String[] args) {
	try {
	    String datafile = "data.txt";
	    FileReader fin = new FileReader(datafile);
	    DefaultTableModel m = createTableModel(fin,
		    new Vector<Object>(Arrays.asList(
			    new String[] { "a", "b", "c" })));
	    JFrame f = new JFrame();
	    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    f.getContentPane().add(new JScrollPane(new JTable(m)));
	    f.setSize(200, 300);
	    f.setVisible(true);
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    /**
     * 
     *
     * @param in A CSV input stream to parse
     * @param headers A Vector containing the column headers. If this is null, it's assumed
     * that the first row contains column headers
     *
     * @return A DefaultTableModel containing the CSV values as type String
     */
    public static DefaultTableModel createTableModel(Reader in,
	    Vector<Object> headers) {
	DefaultTableModel model = null;
	Scanner s = null;

	try {
	    Vector<Vector<Object>> rows = new Vector<Vector<Object>>();
	    s = new Scanner(in);

	    while (s.hasNextLine()) {
		rows.add(new Vector<Object>(Arrays.asList(s.nextLine()
				.split("\\s*,\\s*"))));
	    }

	    if (headers == null) {
		headers = rows.remove(0);
		model = new DefaultTableModel(rows, headers);
	    } else {
		model = new DefaultTableModel(rows, headers);
	    }

	    return model;
	} finally {
	    s.close();
	}
    }
}

