无意中发现了一个巨牛的人工智能教程,忍不住分享一下给大家。很通俗易懂,重点是还非常风趣幽默,像看小说一样。网址是https://blog.csdn.net/jiangjunshow/article/details/77338485
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>4.4</version>
</dependency>
import com.opencsv.bean.CsvBindByName;
public class Bill {
@CsvBindByName(column = "订单号")
private String orderid;
@CsvBindByName(column = "完成时间")
private String time;
@CsvBindByName(column = "金额")
private Double amount;
}
#
的行都过滤掉不处理。import com.opencsv.bean.CsvToBeanFilter;
public class MyCsvFilter implements CsvToBeanFilter {
@Override
public boolean allowLine(String[] line) {
if (line[0].startsWith("#")) {
return false;
}
return true;
}
}
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import com.opencsv.bean.CsvToBean;
import com.opencsv.bean.CsvToBeanBuilder;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
public class MyCsvKit {
public static List<Bill> ReadCsv(String fileName) throws IOException {
InputStreamReader is = new InputStreamReader(new FileInputStream(fileName), "GBK");//注意此处的编码格式,我之前遇到了用utf-8读取出来全是null的问题
HeaderColumnNameMappingStrategy<Bill> mappingStrategy = new HeaderColumnNameMappingStrategy<>();
mappingStrategy.setType(Bill.class);
CsvToBean<Bill> build = new CsvToBeanBuilder<Bill>(is)
.withMappingStrategy(mappingStrategy)
.withFilter(new MyCsvFilter()) //上面建好的过滤器
.withSeparator(',') //逗号分隔符文件当然使用,分隔,当然也有例外
.withSkipLines(4) //意思是跳过前面几行后再读取
.withIgnoreQuotations(true)
.build();
List<Bill> billList = build.parse();
return billList;
}
}
完!