Java读取和写入CSV文件工具类(list<list>)
备注:从list<list<String>>写入,读取到list<list<String>>
工具类CsvUtil.java
package com.xxx.utils;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author : HMF
* @ClassName CsvUtil
* @description 读取和写入csv的工具类
* @date: 2022/2/25 21:37
**/
public class CsvUtil {
/**
* 读取CSV格式的文档数据
* @param filePath CSV格式的文件路劲
* @return dataList csv数据读取放入二维list中。
*/
public static List<List<String>> readCSVFileData(String filePath){
BufferedReader reader=null;
List<List<String>> dataList=new ArrayList<>();
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"));
}catch(FileNotFoundException | UnsupportedEncodingException e){
e.printStackTrace();
}
try{
String line=null;
while ((line=reader.readLine())!=null){
String aa[]=line.split(",");
List<String> cellList= Arrays.asList(aa);
//System.out.println(cellList);
dataList.add(cellList);
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (reader != null) {
//释放资源
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return dataList;
}
/**
* 读取CSV格式的文档数据
* @param filePath CSV格式的文件路劲
* @param dataList 需要写入的数据
* @return dataList csv数据读取放入二维list中。
*/
public static void writeCSVFileData(String filePath,List<List<String>> dataList){
BufferedWriter bw=null;
try {
bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "UTF-8"));
for(int i = 0; i<dataList.size(); i++) {
bw.write(dataList.get(i).get(0)+","+dataList.get(i).get(1));
bw.newLine();
}
} catch (FileNotFoundException e) {
//e.printStackTrace();
System.out.println(e);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (bw != null) {
bw.flush();
//释放资源
bw.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
调用
import java.util.ArrayList;
import java.util.List;
import com.xxx.utils.CsvUtil;
/**
* @author : HMF
* @ClassName ReadFileTest
* @description TODO
* @date: 2022/2/25 21:37
**/
public class ReadFileTest {
public static void main(String[] args) {
List<List<String>> dataList2=new ArrayList<>();
List<String> a1=new ArrayList<>();
a1.add("序号");
a1.add("姓名");
dataList2.add(a1);
List<String> a2=new ArrayList<>();
a2.add("1");
a2.add("张三");
dataList2.add(a2);
List<String> a3=new ArrayList<>();
a3.add("2");
a3.add("李四");
dataList2.add(a3);
CsvUtil.writeCSVFileData("./test.csv",dataList2);
//读取
List<List<String>> dataList=CsvUtil.readCSVFileData("./test.csv");
for(int i = 0; i<dataList.size(); i++){
if(i !=0) {
//System.out.println(dataList.get(i));
String id=dataList.get(i).get(0);
String name=dataList.get(i).get(1);
System.out.println(id+" "+name);
}
}
}
}
执行结果
list参考:Java中List集合的常用方法