Created
January 20, 2019 08:22
-
-
Save sengupta-saikat/fcf176cb210e5d8f4a3275cb74c2b812 to your computer and use it in GitHub Desktop.
Converts multiple csv files in a singe json file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.sai; | |
import com.google.common.collect.MultimapBuilder; | |
import com.google.common.collect.SetMultimap; | |
import com.google.gson.GsonBuilder; | |
import org.apache.commons.csv.CSVFormat; | |
import org.apache.commons.csv.CSVParser; | |
import org.apache.commons.csv.CSVRecord; | |
import java.io.File; | |
import java.io.FileReader; | |
import java.io.IOException; | |
import java.io.Reader; | |
import java.util.List; | |
import java.util.stream.Stream; | |
public class CsvToJson { | |
public static List<CSVRecord> getCsvRecords(String filePath) { | |
try (Reader in = new FileReader(filePath)) { | |
Iterable<CSVRecord> records = CSVFormat.EXCEL.withFirstRecordAsHeader().parse(in); | |
return ((CSVParser) records).getRecords(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
return null; | |
} | |
public static String convertToJson(Object obj) { | |
return new GsonBuilder().setPrettyPrinting().create().toJson(obj); | |
} | |
public static File[] getCsvFiles(String csvFileDir) { | |
return new File(csvFileDir).listFiles((d, name) -> name.toLowerCase().endsWith(".csv")); | |
} | |
public static void main(String[] args) { | |
SetMultimap<String, String> setMultimap = MultimapBuilder.hashKeys().hashSetValues().build(); | |
String csvFileDir = "./src/main/resources/data"; | |
Stream.of(getCsvFiles(csvFileDir)).forEach(file -> { | |
List<CSVRecord> records = getCsvRecords(file.getAbsolutePath()); | |
records.forEach(record -> record.toMap().forEach(setMultimap::put)); | |
}); | |
System.out.println(convertToJson(setMultimap.asMap())); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment