有时候我们需要读取.csv文件并将其中的数据处理成json对象以便后续处理,在这里整理了简单的处理流程。

1. 代码实现

1)引入依赖

<dependency><groupId>net.sf.opencsv</groupId><artifactId>opencsv</artifactId><version>2.3</version>
</dependency>

2)新建controller层

@RestController
@RequestMapping("/read")
@CrossOrigin(value = "*",  maxAge = 3600)
public class ReadFileController {@Resourceprivate ReadCSVServer server;@RequestMapping(value = "/csv", method = RequestMethod.POST)public JSONObject readCSVFil(@RequestBody JSONObject get) throws IOException,JSONException{JSONObject output = new JSONObject();String filePath = get.getString("filePath");filePath.replace("\\", "/");Integer counter = server.csv2txt(filePath);output.put("msg", "succeed");output.put("data", "已处理"+counter+"条数据。");return output;}}

3)新建server层

此处示例是将.csv文件中数据转换成json对象,并以可以直接导入mongodb数据库的格          式写入到.json文件,实际使用中也可以跳过写入文件这一步直接存入数据库。

@Service
public class ReadCSVServer {/*** 读取路径下所有.csv文件* @return List<String>* */public List<String> getFileInPath(String filePath) {List<String> csvList = new ArrayList<>();File f = new File(filePath);File[] ts = f.listFiles();for (int i=0;i<ts.length;i++) {if (ts[i].isFile()) {String fileName = ts[i].toString();//获取最后一个.的位置int lastIndexOf = fileName.lastIndexOf(".");//获取文件的后缀名String suffix = fileName.substring(lastIndexOf);if (suffix.equals(".csv")) {csvList.add(fileName);}}}return csvList;}/*** 将.csv文件逐个处理并写入到json文件中;相当于main方法* @return Integer* */public Integer csv2txt(String filePath) throws IOException,JSONException{List<String> list = getFileInPath(filePath);int counter = 0;if (list != null) {for (String fileName : list) {counter += readCSVAndWrite(fileName, filePath);}}return counter;}public Integer readCSVAndWrite(String fileName, String filePath) throws IOException,JSONException {List<String[]> list = new ArrayList<>();FileInputStream inputStream = null;Scanner sc = null;int counter = 0;try {inputStream = new FileInputStream(fileName);sc = new Scanner(inputStream, "UTF-8");String headLine = new String();String[] headArray = null;if (sc.hasNextLine()) {headLine = sc.nextLine();headArray = headLine.split(",");}while (sc.hasNextLine()) {//因为.csv文件是按逗号分割的,为避免字段中含逗号而分割错误,先进行处理String line = sc.nextLine();String[] strArray = line.split(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)");if (strArray.length!=0) {list.add(strArray);counter++;}//为避免数据量过于庞大导致内存溢出,分批处理if (list.size() == 20000) {List<JSONObject> jsons = csv2JSON(headArray, list);writeObj(jsons, filePath, fileName);list.clear();} else if (!sc.hasNextLine()) {List<JSONObject> jsons = csv2JSON(headArray, list);writeObj(jsons, filePath, fileName);}}// note that Scanner suppresses exceptionsif (sc.ioException() != null) {throw sc.ioException();}} finally {if (inputStream != null) {inputStream.close();}if (sc != null) {sc.close();}}return counter;}/*** 将csv中的一行数据转换成一个一级json* @param keys json的key,顺序需与csv中的value对应* @param values csv中数据作为value* @return*/public JSONObject csv2JSON(String[] keys, String[] values) throws JSONException {JSONObject json = new JSONObject();for (int i = 0; i < keys.length; i++) {try{String value = values[i].replace("\"", "");json.put(keys[i],value);}catch (ArrayIndexOutOfBoundsException e){}}return json;}/*** 将csv的每一行数据都转换成一级json,返回json数组* @param keys json的key,顺序需与csv中的value对应* @param stringsList 读取csv返回的List<String[]>* @return*/public List<JSONObject> csv2JSON(String[] keys,List<String[]> stringsList) throws JSONException {List<JSONObject> jsons = new ArrayList<JSONObject>() {};int index = 0 ;for (String[] strings : stringsList) {JSONObject json = this.csv2JSON(keys, strings);jsons.add(json);}return jsons;}/*** 将处理完后的数据存入.json文件中* @return*/public void writeObj(List<JSONObject> jsonObjects, String path, String fileName) throws IOException {String newFileName = fileName.replace(".csv", ".json");try {// 防止文件建立或读取失败,用catch捕捉错误并打印,也可以throw/* 写入Txt文件 */File writename = new File(path);// 相对路径,如果没有则要建立一个新的output。txt文件if(!writename.exists()){writename.mkdirs();}writename = new File(newFileName);// 相对路径,如果没有则要建立一个新的output。txt文件writename.createNewFile(); // 创建新文件BufferedWriter out = new BufferedWriter(new FileWriter(writename, true));for (JSONObject jsonObject: jsonObjects) {out.write(jsonObject.toString()+"\n");}System.out.println("写入成功!");out.flush(); // 把缓存区内容压入文件out.close(); // 最后记得关闭文件} catch (Exception e) {e.printStackTrace();}}}

2. 实例测试

注:文件过大的话处理速度会很慢,所以后续会更新多线程处理版本的实例

Springboot读取.csv文件并转化为JSON对象相关推荐

  1. 读取CSV文件内容,将其转换成JSON字符串输出

    CsvToJsonUtil 工具类作用:读取CSV文件内容,将其转换成JSON字符串输出 转换工具类代码如下: package com.test.util;import java.io.*; impo ...

  2. python csv读取-Python读取csv文件(详解版,看了无师自通)

    前面程序展示的数据都是直接通过程序给出的,但实际应用可能需要展示不同来源(比如文件.网络).不同格式(比如 csv.JSON)的数据,这些数据可能有部分是损坏的,因此程序需要对这些数据进行处理. cs ...

  3. python怎么读取csv文件-Python读取csv文件(详解版,看了无师自通)

    前面程序展示的数据都是直接通过程序给出的,但实际应用可能需要展示不同来源(比如文件.网络).不同格式(比如 csv.JSON)的数据,这些数据可能有部分是损坏的,因此程序需要对这些数据进行处理. cs ...

  4. python批量读取csv文件-使用Python读写csv文件的三种方法

    行之间无空行十分重要,如果有空行或者数据集中行末有空格,读取数据时一般会出错,引发[list index out of range]错误.PS:已经被这个错误坑过很多次! 使用python I/O写入 ...

  5. 离线轻量级大数据平台Spark之读取CSV文件实例

    Spark的RDD数据集很适合处理轻量文件,一般场景下是excel文件,可以将excel文件另存为CSV(逗号分隔),Spark读取CSV文件形成RDD. 1.序列化类Record,用于保存字段 pa ...

  6. python打开并读取csv文件_!python3中使用使用read_csv( )读取csv文件,文件路径中含有中文,无法读取怎么处理?...

    python3如何根据csv文件的列的内容,自动建数据库表 你好,csv格式的和excel格式是差不多的, 下面是读取excel的一些函数,希望帮到你: # -*- coding: cp936 -*- ...

  7. python3.7读取csv文件_Python3 读取csv文件

    使用pandas 读取csv文件前几行数据 文件内容如下: 先读取标题: importpandas as pd path= r'C:\Users\dhw\Desktop\work\term paper ...

  8. python怎么读取csv文件-python怎么读取csv文件

    Python读写csv文件 前言逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本).纯文 ...

  9. python怎么读取csv文件-使用Python读写csv文件的三种方法

    行之间无空行十分重要,如果有空行或者数据集中行末有空格,读取数据时一般会出错,引发[list index out of range]错误.PS:已经被这个错误坑过很多次! 使用python I/O写入 ...

最新文章

  1. 重磅福利!60篇近两年高影响因子环境污染微生态相关文献合集免费领取
  2. 清华大学张悠慧:超越冯·诺依曼模型,实现软硬件去耦合的类脑计算(附视频)
  3. 解决:夜神模拟器连不上adb的问题
  4. FileCoin (1) 初步介绍
  5. struct linger
  6. python 并发编程 多线程 event
  7. linux命令取ip,linux下命令取IP地址的多种方法
  8. UI素材模板|app ui界面的导航设计都有哪些?
  9. C语言实现键盘记录器
  10. H5和小程序区别详解
  11. 二阶矩阵转置怎么求_矩阵的转置怎么求 详情介绍
  12. 加州大学欧文分校 计算机专业,加州大学欧文分校排名及各专业排名
  13. 计算机控制分离性原理是什么,分离原理
  14. iOS开发工程师常见面试题及答案
  15. 学前端是去培训班还是自学好?
  16. 谁教会老公出轨外面养情人
  17. 更新品牌与Z世代交互方式|朋氪元宇宙即将内测
  18. 基于RTP协议的IP电话QoS监测及提高策略
  19. 艾媒咨询:2015年度中国智能路由器市场监测报告
  20. Dev C++或者 codeblocks编译出现 [Error] ld returned 1 exit status

热门文章

  1. 波士顿动力真的无可企及吗?一步步剖析四足机器人技术(二)
  2. linux中的链接符号
  3. [9i] 2019新年临近,常用的关于新年方面的单词和祝福语
  4. 使用EPPlus,操作excel,对日期格式的处理方式
  5. 刘韧:我对股票最大的迷思是相信物极必反
  6. 项目框架:登录跳转页面
  7. CVE-2016-7124漏洞复现
  8. 使用RPC的接口转账
  9. 产品经理都是这样做产品规划的(下)
  10. mybatis中怎样使用having?