java利用org.apache.commons.csv操作csv文件

public static void readCsv(String csvPath, boolean readHeader) throws IOException {
    Reader in = new InputStreamReader(new FileInputStream(csvPath), StandardCharsets.UTF_8);
    Iterable<CSVRecord> records;
    if (readHeader) {//读取表头
        records = CSVFormat.RFC4180.parse(in);
    } else {//不读取表头,默认第一行为header
        records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
    }
    for (CSVRecord record : records) {
        System.out.println(record.toString());//打印整行内容
        System.out.println(record.size());//打印本行有多少个值
        System.out.println(record.getRecordNumber());//打印本行行数
        System.out.println(record.get(0));//按索引返回对应值
        System.out.println(record.get("id"));//按名称返回对应值
    }
    in.close();
}

//返回最后一行的行数
public static long getTotalLines(String csvPath, boolean readHeader) throws IOException {
    Reader in = new InputStreamReader(new FileInputStream(csvPath), StandardCharsets.UTF_8);
    Iterable<CSVRecord> records;
    if (readHeader) {//读取表头
        records = CSVFormat.RFC4180.parse(in);
    } else {//不读取表头,默认第一行为header
        records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
    }
    long lines = 0;
    for (CSVRecord record : records) {
        lines = record.getRecordNumber();//打印本行行数
    }
    in.close();
    return lines;//返回最后一行的行数
}

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 点我我会动 设计师:白松林 返回首页