0

I am new to java and csv files. I would like to store a csv file in a multidimensional string array but I don't know the number of lines in the file and its fields.

So how can I get the number of lines (e.g. rows)

String[][] myStringArray = new String [X][5];

need the value of X

Also i would like to write to a csv file having header

ID,Time,Name,Comment
14,Mon Apr 06 23:48:45 PDT 2009,scotthamilton,"App"

which libraries are best to use

Thanks

rolfl
  • 17,539
  • 7
  • 42
  • 76
user2802027
  • 75
  • 1
  • 12

2 Answers2

0

SupeCSV is an option: http://supercsv.sourceforge.net/examples_writing.html
CSVMapWriter might be a solution for writing a header and mapping your columns to your header:

    final String[] header = new String[] { "ID","Time", "Name", "Comment" };

CSVMapReader or CSVBeanReader can be used to read a CSV file with an arbitrary number of lines, then return a Map which can then be converted to a two-dimensional String array.

Note: Take notion of the fact that CSV separators are sometimes different (Excel export etc.), even though it is called Comma-Separated-Values and might cause parsing problems. Preferences are set like so:

   mapReader = new CsvMapReader(new FileReader(path), CsvPreference.EXCEL_NORTH_EUROPE_PREFERENCE); 
maryokhin
  • 1,058
  • 13
  • 20
0

I would suggest you to store your file into self-growing ArrayList and then call List#toArray method to convert the result to multidimensional array.

E.g, something like that:

List<List<String>> list = new ArrayList<List<String>>();

List<String> item;
list.add(item = new ArrayList<String>());
item.add("foo1"); 
item.add("bar1");

list.add(item = new ArrayList<String>());
item.add("foo2"); 
item.add("bar2");

List<String> [] arr = list.toArray(new ArrayList<String>(list.size()));

int maxSize = -1;
for(int a=0;a<arr.length;a++)
    if(maxSize < arr[a].size())
        maxSize = arr[a].size();

String [][] arr2 = new String[arr.length][maxSize];
for(int a=0;a<arr.length;a++)
    arr2[a] = arr[a].toArray(new String[maxSize]);

System.out.println(arr2);
Archer
  • 5,073
  • 8
  • 50
  • 96