Java reads CSV, reads CSV with commas and newlines

JAVA read CSV file

I searched java on the Internet to read CSV , and saw that many posts wrote that it was read in this way.
It is possible to read general CSV files in this way, but it will not work when encountering some special ones ( such as those with commas in the content and line breaks in the content )

public static List<String> importCsv(File file){
    
    
    List<String> dataList=new ArrayList<String>();
    
    BufferedReader br=null;
    try {
    
     
        br = new BufferedReader(new FileReader(file));
        String line = ""; 
        while ((line = br.readLine()) != null) {
    
     
            dataList.add(line);
        }
    }catch (Exception e) {
    
    
    }finally{
    
    
        if(br!=null){
    
    
            try {
    
    
                br.close();
                br=null;
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }
    }

    return dataList;
}

Here's a better way to read CSV

Preparation
  1. Import the hutool package
<!-- hutool工具类-->
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.3.8</version>
</dependency>
  1. Prepare CSV file (content with comma, content with line break)
    CSV file image screenshot
标题1,标题2,标题3,标题4
内容1,嘻嘻嘻嘻嘻嘻擦擦擦擦擦擦,tyyyyyy,tttt
得得,得的,"芙蓉峰润肤,
乳芙蓉峰,润肤乳",,feffrfrfr

Read as CsvRow
public static void main(String[] args) {
    
    
    CsvReader reader = CsvUtil.getReader();
    //从文件中读取CSV数据
    CsvData data = reader.read(FileUtil.file("/xxx/工作簿1.csv"));
    List<CsvRow> rows = data.getRows();
    int i = 0;
    //遍历行
    for (CsvRow csvRow : rows) {
    
    
        i++;
        System.out.print("第"+i+"行   ");
        //getRawList返回一个List列表,列表的每一项为CSV中的一个单元格(既逗号分隔部分)
        //Console.log(csvRow.getRawList());
        System.out.print(csvRow.get(0)+"   ");
        System.out.print(csvRow.get(1)+"   ");
        System.out.print(csvRow.get(2)+"   ");
        System.out.println(csvRow.get(3));
    }
}

read as bean
package org.jeecg.modules.system.service;

import cn.hutool.core.annotation.Alias;
import lombok.Data;

@Data
public class TestBean {
    
    

    @Alias("标题1")
    private String title1;

    @Alias("标题2")
    private String title2;

    @Alias("标题3")
    private String title3;

    @Alias("标题4")
    private String title4;
}

use

final CsvReader reader = CsvUtil.getReader();
//假设csv文件在classpath目录下
final List<TestBean> result = reader.read(
        ResourceUtil.getUtf8Reader("/xxx/工作簿1.csv"), TestBean.class);
System.out.println(result);

Guess you like

Origin blog.csdn.net/pan_jiabao/article/details/121743906