Java CSV to Array and Array to CSV

This is a little example in Java to convert a CSV String into an Multidimensional Array, after that i convert the Array back into a CSV String, you could choose the delimiter by yourself. In this case i take the “-” to see the different:

public class HelloWorld{

     public static void main(String []args){
        String str="1;2;3\n4;5;6\n7;8;9\n10;11;12";
        System.out.println(str);
        String[][] out = csv2array(str);
        System.out.print(array2csv(out,"-"));
        
     }
     
    public static int count(String s, char c) {
        return s.length()==0 ? 0 : (s.charAt(0)==c ? 1 : 0) + count(s.substring(1),c);
    }
    
    public static String[][] csv2array(String str){
        String[] parts   = str.split("\n");
        String[][] out = new String[count(str,'\n')+1][count(parts[0],';')+1];
        for(int i = 0;i< parts.length;++i){
            if(!parts[i].equals("")){
                out[i] = parts[i].split(";");
            }
        }
        return(out);
     }
     
     public static String array2csv(String[][] in,String delim){
         String out = "";
        for(int x = 0;x < in.length;x++){
        for(int y = 0;y < in[x].length;y++){
            out += (in[x][y]);
            if(y!=in[x].length-1){
                out += delim;
            }
        }
        out += ("\n");
        }
        return(out);
     }
     
}

This is the Output, fist block separated with the “;” is the input and with “-” is the output:

1;2;3
4;5;6 
7;8;9
10;11;12
1-2-3
4-5-6
7-8-9
10-11-12

2 thoughts on “Java CSV to Array and Array to CSV”

  1. For most up-to-date news you have to pay a quick visit world-wide-web
    and on world-wide-web I found this site as a best web page for
    most up-to-date updates.

  2. Hello, its nice piece of writing regarding media print,
    we all be familiar with media is a impressive source of
    information.

Leave a Reply

Your email address will not be published.

four × 5 =