public Map < String , List < String > > parseCSV ( final String headers , final String file , final String separator , final String encoding ) throws IOException { LOG . info ( "Parsing CSVs from file: " + file + " with headers: " + headers + " separator: " + separator ) ; Map < String , List < String > > result = new HashMap < String , List < String > > ( ) ; BufferedReader reader = null ; try { String [ ] headersArr = headers . split ( "," ) ; reader = new BufferedReader ( new InputStreamReader ( new FileInputStream ( file ) , encoding ) ) ; String line = null ; while ( ( line = reader . readLine ( ) ) != null ) { String [ ] lines = line . split ( separator ) ; if ( lines . length != headersArr . length ) { throw new IOException ( "Too many or too little theaders!" ) ; } for ( int i = 0 ; i < lines . length ; i ++ ) { List < String > currentHeader = result . get ( headersArr [ i ] . trim ( ) ) ; if ( currentHeader == null ) { currentHeader = new ArrayList < String > ( ) ; result . put ( headersArr [ i ] . trim ( ) , currentHeader ) ; } currentHeader . add ( lines [ i ] . trim ( ) ) ; } } } finally { if ( reader != null ) { reader . close ( ) ; } } LOG . info ( "Result of parsing CSV: " + result ) ; return result ; }
Parses a CSV file based on the header received .