java list to csv_Java之CSV文件转List数据工具

本文介绍了一个Java工具类CsvToListUtil,用于处理CSV文件的读取与解析。该工具支持自定义编码方式,能够处理包含特殊字符的CSV文件,并提供了一种处理跨行双引号的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.powersi.biz.park.network.util;

import java.io.*;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;/**

* @Description TODO

* @Author zhouruntao

* @Date 2020/11/11 11:18*/

public classCsvToListUtil {/**

* CSV文件编码*/

private static final String ENCODE = "UTF-8";/**

* 读取CSV文件得到List,默认使用UTF-8编码

* @param fileName 文件路径

* @return*/

public static ListgetLines(String fileName) {returngetLines(fileName, ENCODE);

}/**

* 读取CSV文件得到List

* @param fileName 文件路径

* @param encode 编码

* @return*/

public static ListgetLines(String fileName, String encode) {

List lines = new ArrayList();

BufferedReader br= null;

InputStreamReader isr= null;

FileInputStream fis= null;try{

fis= newFileInputStream(fileName);

isr= newInputStreamReader(fis, encode);

br= newBufferedReader(isr);

String line;while ((line = br.readLine()) != null) {

StringBuilder sb= newStringBuilder();

sb.append(line);

boolean readNext= countChar(sb.toString(), '"', 0) % 2 == 1;//如果双引号是奇数的时候继续读取。考虑有换行的是情况

while(readNext) {

line=br.readLine();if (line == null) {return null;

}

sb.append(line);

readNext= countChar(sb.toString(), '"', 0) % 2 == 1;

}

lines.add(sb.toString());

}

}catch(Exception e) {//log.error("Read CSV file failure :{}", e);

System.out.println("Read CSV file failure :{}" +e);

}finally{try{if (br != null) {

br.close();

}if (isr != null) {

isr.close();

}if (fis != null) {

fis.close();

}

}catch(IOException e) {//log.error("Close stream failure :{}", e);

System.out.println("Close stream failure :{}" +e);

}

}returnlines;

}public static ListgetLines(File file, String encode) {

List lines = new ArrayList();

BufferedReader br= null;

InputStreamReader isr= null;

FileInputStream fis= null;try{

fis= newFileInputStream(file);

isr= newInputStreamReader(fis, encode);

br= newBufferedReader(isr);

String line;while ((line = br.readLine()) != null) {

StringBuilder sb= newStringBuilder();

sb.append(line);

boolean readNext= countChar(sb.toString(), '"', 0) % 2 == 1;//如果双引号是奇数的时候继续读取。考虑有换行的是情况

while(readNext) {

line=br.readLine();if (line == null) {return null;

}

sb.append(line);

readNext= countChar(sb.toString(), '"', 0) % 2 == 1;

}

lines.add(sb.toString());

}

}catch(Exception e) {//log.error("Read CSV file failure :{}", e);

System.out.println("Read CSV file failure :{}" +e);

}finally{try{if (br != null) {

br.close();

}if (isr != null) {

isr.close();

}if (fis != null) {

fis.close();

}

}catch(IOException e) {//log.error("Close stream failure :{}", e);

System.out.println("Close stream failure :{}" +e);

}

}returnlines;

}public staticString[] fromCSVLine(String source) {return fromCSVLine(source, 0);

}/**

* 把CSV文件的一行转换成字符串数组。指定数组长度,不够长度的部分设置为null

* @param source

* @param size

* @return*/

public static String[] fromCSVLine(String source, intsize) {

List list=fromCSVLineToArray(source);if (size

size=list.size();

}

String[] arr= newString[size];

list.toArray(arr);returnarr;

}public staticList fromCSVLineToArray(String source) {if (source == null || source.length() == 0) {return newArrayList();

}int currentPosition = 0;int maxPosition =source.length();int nextComa = 0;

List list= newArrayList();while (currentPosition

nextComa=nextComma(source, currentPosition);

list.add(nextToken(source, currentPosition, nextComa));

currentPosition= nextComa + 1;if (currentPosition ==maxPosition) {

list.add("");

}

}returnlist;

}/**

* 把字符串类型的数组转换成一个CSV行。(输出CSV文件的时候用)

*

* @param arr

* @return*/

public staticString toCSVLine(String[] arr) {if (arr == null) {return "";

}

StringBuilder sb= newStringBuilder();for (int i = 0; i < arr.length; i++) {

String item=addQuote(arr[i]);

sb.append(item);if (arr.length - 1 !=i) {

sb.append(",");

}

}returnsb.toString();

}/**

* 将list的第一行作为Map的key,下面的列作为Map的value

* @param list

* @return*/

public static List> parseList(Listlist) {

List> resultList = new ArrayList>();

String firstLine= list.get(0);

String[] fields= firstLine.split(",");for (int i = 1; i < list.size(); i++) {

String valueLine= list.get(i);

String[] valueItems=CsvToListUtil.fromCSVLine(valueLine);

Map map = new HashMap();for (int j = 0; j < fields.length; j++) {

map.put(fields[j], valueItems[j]);

}

resultList.add(map);

}returnresultList;

}/**

* 字符串类型的List转换成一个CSV行。(输出CSV文件的时候用)

*

* @param strArrList

* @return*/

public staticString toCSVLine(ArrayList strArrList) {if (strArrList == null) {return "";

}

String[] strArray= newString[strArrList.size()];for (int idx = 0; idx < strArrList.size(); idx++) {

strArray[idx]= (String) strArrList.get(idx);

}returntoCSVLine(strArray);

}/**

* 计算指定字符的个数

*

* @param str 文字列

* @param c 字符

* @param start 开始位置

* @return 个数*/

private static int countChar(String str, char c, intstart) {int index =str.indexOf(c, start);return index == -1 ? 0 : countChar(str, c, index + 1) + 1;

}/**

* 查询下一个逗号的位置。

*

* @param source 文字列

* @param st 检索开始位置

* @return 下一个逗号的位置。*/

private static int nextComma(String source, intst) {int maxPosition =source.length();

boolean inquote= false;while (st

}else if ('"' ==ch) {

inquote= !inquote;

}

st++;

}returnst;

}/**

* 取得下一个字符串

*

* @param source

* @param st

* @param nextComma

* @return*/

private static String nextToken(String source, int st, intnextComma) {

StringBuilder strb= newStringBuilder();int next =st;while (next

strb.append(ch);

next++;

}

}else{

strb.append(ch);

}

}returnstrb.toString();

}/**

* 在字符串的外侧加双引号。如果该字符串的内部有双引号的话,把"转换成""。

*

* @param item 字符串

* @return 处理过的字符串*/

private staticString addQuote(String item) {if (item == null || item.length() == 0) {return "\"\"";

}

StringBuilder sb= newStringBuilder();

sb.append('"');for (int idx = 0; idx < item.length(); idx++) {char ch =item.charAt(idx);if ('"' ==ch) {

sb.append("\"\"");

}else{

sb.append(ch);

}

}

sb.append('"');returnsb.toString();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值