`

单个csv转换json合并所有csv

 
阅读更多
主类
public static void main(String[] args)throws Exception {
File file = new File("K:/input");
File[] list = file.listFiles();
List list1 = new ArrayList();
LinkedHashMap map = null;
String[] title = null;
for (File file1:list){
map = read(file1);
list1.addAll((ArrayList)map.get("2"));
};
FileUtils.writeStringToFile(new File("C:/csv2.csv"), Json2Csv(JSonUtil.toJson(list1)));
}
public static String Json2Csv(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String csv = CDL.toString(jsonArray);
return csv;
}

 读取csv转json

 /**
     * 读取csv所有数据转换为json
     */
    public static LinkedHashMap read(File file) {
        LinkedHashMap result = new LinkedHashMap();
        ArrayList<LinkedHashMap> list = null;
        String[] title = null;
        try {
            CSVReader csvReader = new CSVReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            title = csvReader.readNext();//标题
            List<String[]> lists = csvReader.readAll();//内容 todo 目前已内容
            list = new ArrayList();
            LinkedHashMap map = null;
            for (int k = 0; k < lists.size(); k++) {//lists的规格有多少
                map = new LinkedHashMap();
                for (int i = 0; i < lists.get(k).length; i++) {
                    map.put(title[i], lists.get(k)[i]);
                }
                list.add(map);
            }
            csvReader.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        result.put("1", title);
        result.put("2", list);
        return result;
    }

 

 

 

分享到:
评论
1 楼 sky夜弦 2018-10-19  
    

相关推荐

Global site tag (gtag.js) - Google Analytics