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("[\n"); 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行數據列和表頭列個數不一致\r\n%s", lineCnt, line); System.err.println(mString); break; } String jsonStr = stringToJson(header, lineData); //將最后一行的逗號去掉 if (counts == lineCnt) { jsonStr = jsonStr.replaceAll(".$", ""); } writer.write(jsonStr); writer.write("\r\n"); // 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("轉換完成"); } }