Java使用Opencv读取csv文件

本文介绍了如何使用Java和OpenCSV库处理CSV文件,包括读取带BOM的文件、表头中文映射、实体映射和写入CSV操作,以及Book实体的定义。重点展示了如何通过HeaderColumnNameTranslateMappingStrategy进行中文表头的正确解析。
摘要由CSDN通过智能技术生成

1 需要的jar

<!-- 需要的jar包 -->
<dependency>
    <groupId>com.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>4.6</version>
</dependency>
​
<!-- 使用opencsv必须的jar包 -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.11</version>
</dependency>
​
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.4</version>
</dependency>

<!-- 如果读取带BOM的文件,需要使用下面的包,不使用会出现第一列读不出来 -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

2 表头中文映射读取

2.1 java代码


/**
 * 使用表头中文映射读取CSV文件,表头为"姓名"、"尺寸"、"描述"
 */
public List<Book> readCsv() {
    try {
        // 创建输入流
        FileInputStream fileInputStream = new FileInputStream(this.hotwordsCsvPath);
        // 读取带BOM的CSV文件需要使用BOMInputStream
        BOMInputStream bomInputStream = new BOMInputStream(fileInputStream);

        // 创建Reader
        InputStreamReader inputStreamReader = new InputStreamReader(bomInputStream, StandardCharsets.UTF_8);
        CSVReader csvReader = new CSVReaderBuilder(inputStreamReader).build();

        // 设置实体映射策略
        HeaderColumnNameTranslateMappingStrategy<Book> strategy = new HeaderColumnNameTranslateMappingStrategy<>();
        strategy.setType(Book.class);
        Map<String, String> columnMapping = new HashMap<>();
        columnMapping.put("姓名", "name");
        columnMapping.put("尺寸", "height");
        columnMapping.put("描述", "desc");

        // 设置映射
        strategy.setColumnMapping(columnMapping);

        // 实体映射
        CsvToBeanBuilder<Book> csvToBeanBuilder = new CsvToBeanBuilder<Book>(csvReader);
        csvToBeanBuilder.withSeparator(CSVWriter.DEFAULT_SEPARATOR);
        csvToBeanBuilder.withQuoteChar(CSVWriter.NO_QUOTE_CHARACTER);
        csvToBeanBuilder.withMappingStrategy(strategy);

        CsvToBean csvToBean = csvToBeanBuilder.build();

        // 解析csv
        List list = csvToBean.parse();

        System.out.println(list);

    } catch (IOException e) {
        e.printStackTrace();
    } ;


    return null;
}
 

2.2 csv文件

姓名尺寸描述
中国0,0.8164938785607375中国人民真精神0
中国10.8979758050541083中国人民真精神1

3 简单关系

3.1 java代码

/**
使用默认的方式读取CSV文件,表头为"name"、"height"、"desc";
*/
public List<Book> readCsvSimple(){
    try {
        // 建立Reader
        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("F:\\data\\simple.csv"), StandardCharsets.UTF_8);
        CSVReader csvReader = new CSVReaderBuilder(inputStreamReader).build();
​
        // 实体转换
        CsvToBeanBuilder<Book> csvToBeanBuilder = new CsvToBeanBuilder<Book>(csvReader);
        csvToBeanBuilder.withSeparator(CSVWriter.DEFAULT_SEPARATOR);
        csvToBeanBuilder.withQuoteChar(CSVWriter.NO_QUOTE_CHARACTER);
        csvToBeanBuilder.withType(Book.class);
​
        CsvToBean csvToBean = csvToBeanBuilder.build();
​
        // 解析列表
        List list = csvToBean.parse();
​
        System.out.println(list);
​
    } catch (IOException e) {
        e.printStackTrace();
    };
​
​
    return null;
}
​

3.2 csv文件

techweightdesc
中国0,0.8164938785607375中国人民真精神0
中国10.8979758050541083中国人民真精神1

4 实体

/**
Book实体关系
*/
​
@Data
@NonNull
@NoArgsConstructor
@Component
public class Book {
    private String name;
    private double height;
    private String desc;
​
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
​
    public double getHeight() {
        return height;
    }
    public void setHeight(double height) {
        this.height = height;
    }
​
    public String getDesc() {
        return desc;
    }
    public void setDesc(String desc) {
        this.desc = desc;
    }
}

5 使用item读取csv

try {
    InputStreamReader reader = new InputStreamReader(new FileInputStream(new File(csvPath)), "UTF-8");
    CSVReader csvReader = new CSVReaderBuilder(reader).build();
    Iterator<String[]> iterator = csvReader.iterator();
    // 如果有数据进行遍历读取
    if(iterator.hasNext()){
        // 跳过第一行
        iterator.next();
        
        // 循环读取数据
        while (iterator.hasNext()) {
            // 读取一行的数据
            List<String> list = Arrays.asList(iterator.next());
            // 使用索引读取单元格数据
            System.out.println(list[0]);
        }
    }
    return null;
} catch (IOException e) {
    System.out.println("Read the csv of "+csvPath+" is error !");
    e.printStackTrace();
    return false;
}

6 使用OpenCSV写入CSV

// 使用字符串数组写入CSV
public boolean writeCsvArr(){
    try {
        FileWriter fileWriter = new FileWriter("D:/mybook.csv");
        CSVWriter writer = new CSVWriter(fileWriter);
        String[] row = new String[]{"name", "height", "desc"};
        writer.writeNext(row);

        row = new String[]{"zhangsan", "10", "my desc"};
        writer.writeNext(row);

        writer.close();
        fileWriter.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}


// 含有BOM字符,使用字符串数组写入CSV
public boolean writeCsvArrBom(){
    try {
        byte [] bs = { (byte)0xEF, (byte)0xBB, (byte)0xBF};
        FileOutputStream fileOutputStream = new FileOutputStream("D:/mybook.csv");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        outputStreamWriter.write(new String(bs));

        CSVWriter writer = new CSVWriter(outputStreamWriter);
        String[] row = new String[]{"name", "height", "desc"};
        writer.writeNext(row);

        row = new String[]{"zhangsan", "10", "my desc"};
        writer.writeNext(row);

        writer.close();
        outputStreamWriter.close();
        fileOutputStream.close();

        return true;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return false;
}


// 使用对象列表写入CSV
public boolean writeCsvList(){
    try {

        Writer writer = new FileWriter("D:/mybook.csv");
        StatefulBeanToCsv<Book> beanToCsv = new StatefulBeanToCsvBuilder<Book>(writer).build();

        Book book = new Book();
        book.setDesc("CSV 11 ");
        book.setHeight(11);
        book.setName("Read CSV 11");
        beanToCsv.write(book);

        book = new Book();
        book.setDesc("CSV 22");
        book.setHeight(22);
        book.setName("Read CSV 22");
        beanToCsv.write(book);

        writer.close();
        return true;
    } catch (IOException | CsvRequiredFieldEmptyException | CsvDataTypeMismatchException e) {
        e.printStackTrace();
    }
    return false;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值