• csv文件转换json文件


    import java.io.*;
    import java.util.Arrays;
    import java.util.List;
    
    // CSV文件转 json文件
    // 使用csvToJSon对象的.ConvertToJson方法 带入 csv文件路径及导出路径。
    public class CSVToJSon {
        //cvs文件
        private static String startFile = "E:\xiangshu\积水点位置及经纬度.csv";
        //目标文件
        private static String endFile = "E:\xiangshu\987654.json";
    
        private List<String> stringToList(String s, String sep) {
            if (s == null) {
                return null;
            }
            String[] parts = s.split(sep);
            return Arrays.asList(parts);
        }
    
        //将分割的第一行的表头list和后面的值list进行拼接
        //拼接完后以string返回
        //示例如{"name" : "kevin","sex" : "man"}
        private String stringToJson(List<String> header, List<String> lineData) throws Exception {
    
            if (header == null || lineData == null) {
                throw new Exception("输入不能为null。");
            } else if (header.size() != lineData.size()) {
                throw new Exception("表头个数和数据列个数不等。");
            }
            StringBuilder sBuilder = new StringBuilder();
            sBuilder.append("{ ");
            for (int i = 0; i < header.size(); i++) {
    
                String mString = String.format(""%s": "%s"", header.get(i), lineData.get(i));
                sBuilder.append(mString);
                if (i != header.size() - 1) {
                    sBuilder.append(", ");
                }
            }
            sBuilder.append(" },");
            return sBuilder.toString();
        }
    
        //获取行数
        public int getTotalLines(File file) throws IOException {
            long startTime = System.currentTimeMillis();
            FileReader in = new FileReader(file);
           /*LineNumberReader这个类多了跟踪行号的功能,它定义了setLineNumber(int)和getLineNumber()方法,
           分别起到设置行号和获取行号的作用。默认情况下,行编号从0开始,所以一开始获取行号,就是0了,
           每当换行一次,就会+1,这样来记录行号的。比如,我们调用了setLineNumber(int)方法,
           那么文件指针会跳转到指定的行吗?答案是:不会!因为,它只是起到了设置LineNumber的值的作用,
    */
            LineNumberReader reader = new LineNumberReader(in);
            reader.skip(Long.MAX_VALUE);
            int lines = reader.getLineNumber();
            reader.close();
            long endTime = System.currentTimeMillis();
    
            System.out.println("统计文件行数运行时间: " + (endTime - startTime) + "ms");
            return lines;
        }
    
        public void ConvertToJson(InputStream filePath, OutputStream outPutPath, int count) throws Exception {
            //创建BufferedReader 来读文件
            //创建使用BufferedWriter 来写文件
            InputStreamReader isr = new InputStreamReader(filePath, "utf-8");
            BufferedReader reader = new BufferedReader(isr);
            OutputStreamWriter osw = new OutputStreamWriter(outPutPath, "utf-8");
            BufferedWriter writer = new BufferedWriter(osw);
            int counts = --count;
            try {
    
                String sep = ",";
                //将csv表格第一行构建成string
                String headerStr = reader.readLine();
                if (headerStr.trim().isEmpty()) {
                    System.out.println("表格头不能为空");
                    return;
                }
                //将String字符串通过split(",")csv是以,作分隔符
                // 进行切割输出成List
                List<String> header = stringToList(headerStr, sep);
                String line;
                int lineCnt = 0;
                writer.write("[
    ");
                while ((line = reader.readLine()) != null) {
                    lineCnt++;
                    System.out.println("行数" + line);
                    if (line.trim().isEmpty()) {
                        System.out.println("第" + lineCnt + "行为空,已跳过");
                        continue;
                    }
    
                    List<String> lineData = stringToList(line, sep);
    
                    if (lineData.size() != header.size()) {
                        String mString = String.format("第%d行数据列和表头列个数不一致
    %s", lineCnt, line);
                        System.err.println(mString);
                        break;
                    }
    
                    String jsonStr = stringToJson(header, lineData);
                    //将最后一行的逗号去掉
                    if (counts == lineCnt) {
                        jsonStr = jsonStr.replaceAll(".$", "");
                    }
    
                    writer.write(jsonStr);
                    writer.write("
    ");
                    // lineCnt++;
                    System.out.println(lineCnt);
    
                }
    
                writer.write("]");
            } finally {
                if (reader != null) {
                    reader.close();
                }
                if (writer != null) {
                    writer.close();
                }
            }
        }
    
        public static void main(String[] args) throws Exception {
            //使用Java IO流操作打开/导出文件
    
            InputStream filePath = new FileInputStream(startFile);
            OutputStream outPutPath = new FileOutputStream(endFile);
            File file = new File(startFile);
            CSVToJSon csvToJSon = new CSVToJSon();
            int count = csvToJSon.getTotalLines(file);
            csvToJSon.ConvertToJson(filePath, outPutPath, count);
            System.out.println("转换完成");
        }
    
    }
    

      

  • 相关阅读:
    MongoDB数据类型
    杭电1257
    杭电1716
    杭电1997
    杭电1492
    杭电1208
    杭电1290
    杭电1087
    杭电1568
    杭电1398
  • 原文地址:https://www.cnblogs.com/shuai666/p/15478114.html
Copyright © 2020-2023  润新知