一般都是数据库导出为CSV文件,然后在其他地方,进行数据传输
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student {
private Integer id;
private String name;
private Integer age;
}
使用第三方jar,方便快捷
Maven
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.4</version>
</dependency>
使用方式:
@Test
public void readCSV() {
String srcPath = "C:\\Users\\Administrator\\Desktop\\t_student.csv";
String charset = "utf-8";
try (CSVReader csvReader = new CSVReaderBuilder(new BufferedReader(new InputStreamReader(new FileInputStream(new File(srcPath)), charset))).build()) {
Iterator<String[]> iterator = csvReader.iterator();
iterator.next(); //跳过表头
//创建一个集合用于存储csv文件读取出来的所有数据
List<Student> students=new ArrayList<>();
while (iterator.hasNext()) {
String[] next = iterator.next();//获取每一行的数据
Student student=new Student();
student.setId(Integer.parseInt(openCsvDefault(next[0],"0")));
student.setName(openCsvDefault(next[1],""));
student.setAge(Integer.parseInt(openCsvDefault(next[2],"0")));
students.add(student);
}
System.out.println(students);
} catch (Exception e) {
e.printStackTrace();
}
}
// 为空补默认值
public String openCsvDefault(String str,String m){
if (Strings.isBlank(str)) {
return m;
} else {
return str;
}
}
手动写代码进行读取的csv数据默认是用双引号包起来的,在最后的截取中,如果只按照双引号外的逗号截取,不就是能得到想要的数据了。我们使用正则表达式进行手动截取
@Test
public void show(){
long startTime = System.currentTimeMillis();
try (
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Users\\Administrator\\Desktop\\t_student.csv"))));
) {
//跳过标题
final int size = br.readLine().split(",").length; //切割数据
//创建一个集合用于存储csv文件读取出来的所有数据
List<Student> students=new ArrayList<>();
//开始读取
String line;
do {
line = br.readLine(); //每次读取一行数据
if (!Strings.isBlank(line)) {
String[] strings=new String[size];//保证每一列都是一样的长度
//正则表达式切割,避免中文内包含逗号
String split[] = line.trim().split(",(?=([^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*$)",-1);
for (int i = 0; i < strings.length; i++) {
if (i>=split.length){
break;
}
strings[i]=split[i];
}
System.out.println(Arrays.toString(strings));
Student student=new Student();
student.setId(Integer.parseInt( csvStrDefault(strings[0],"0" )));
student.setName(csvStrDefault(strings[1],""));
student.setAge(Integer.parseInt(csvStrDefault(strings[2],"0")));
students.add(student);
}
}while (line != null);
System.out.println(students);
} catch (Exception e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println("花费时间为:" + (double)(endTime - startTime)/1000+"秒");
}
// 为空补默认值
public String csvStrDefault(String str,String m){
if (Strings.isBlank(str)) {
return m;
} else {
return str.substring(1,str.length()-1);
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/weixin_45203607/article/details/120238455
内容来源于网络,如有侵权,请联系作者删除!