Search code examples
javacsvldif

parse csv format file into java arrays for generating ldif format file


I am a rookie in java coding area, I am trying to parse a csv format file, split with only commas(,) this file includes users' account names and true names, for example, it looks like: tom123,Tom Halland,kelly02,Kelly Chen,..and so on, I want to parse these user's data into something like arrays using java, so I can reuse this array, then to generate ldif format file and import it into LDAP server to create accounts automatically, is there any easier way to do it? or any technical advises for me? Thanks a lot!


Solution

  • I am sharing code snippet from one of my previous assignments. Basically code does following tasks:

    1) Read CSV file line by line

    2) Split each line into token with help of predefined characher(in case of csv it's ',')

    3) Generate a string form of record in desired ldif format

    4) write record to output file

    String inputCSVFile = "/input_folder_path/sample.csv"; 
            BufferedReader bufferedReader = null;
            String lines = "";
            String splitChar = ",";        
            String[] columns;
    
            int count = 0;
    
            try {
    
                PrintStream printStream = new PrintStream(new FileOutputStream("/output_folder_path/e.ldif"));// Step 1
                bufferedReader = new BufferedReader(new FileReader(inputCSVFile));
    
                while ((lines = bufferedReader.readLine()) != null) {
    
    
                    columns = lines.split(splitChar);// Step 2
    
    
                    if (count > 0) {// Step 3 ,4
                        printStream.println("dn: cn="+columns[1]+", ou="+columns[2]+", o=Data"
                                + "\ngivenName: "+columns[0]
                                + "\nsn: "+columns[3]
                                + "\n"
                        );
                    }
                    count++;
    
                }
    
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bufferedReader != null) {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }