使用Apache Commons CSV解析GitHub CSV URL时无法解析表头如何解决
问题原因
BufferedReader读取逻辑错误:while((in.readLine()) != null)已经消费了一行数据,循环体内再次调用in.readLine()会直接跳过已读行,导致CSV第一行的真实表头被丢弃,后续拿到的第一行是实际数据行。调用withFirstRecordAsHeader()时会把数据行解析为表头,而该数据行第一个字段为空,直接触发表头缺失的异常。CSVParser使用逻辑错误:CSVParser需要读取完整的CSV数据流才能完成表头解析和后续行匹配,逐行传入StringReader无法正常完成全局解析。
可行解决方案
直接将完整的输入流传入CSVParser处理,不需要自行逐行读取流内容,修正后代码如下:
@Service public class CoronaVirusDataService { private static String virus_data_url = "https://raw.githubusercontent.com/CSSEGISandData/COVID-19/Aysen_Chile_07032021/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv"; @PostConstruct public void getVirusData() { HttpURLConnection con = null; InputStreamReader inputStreamReader = null; try { URL url = new URL(virus_data_url); con = (HttpURLConnection) url.openConnection(); inputStreamReader = new InputStreamReader(con.getInputStream()); // 直接传入完整流指定首行为表头解析 Iterable<CSVRecord> records = CSVFormat.DEFAULT.withFirstRecordAsHeader().parse(inputStreamReader); for (CSVRecord record : records) { String country = record.get("Country/Region"); System.out.println(country); } } catch(Exception e) { e.printStackTrace(); } finally { // 资源释放 try { if (inputStreamReader != null) { inputStreamReader.close(); } if (con != null) { con.disconnect(); } } catch (Exception ex) { ex.printStackTrace(); } } } }
如果确认CSV本身存在空表头的业务场景,可以追加配置允许空表头避免报错:CSVFormat.DEFAULT.withFirstRecordAsHeader().withAllowMissingColumnNames(true)。
内容的提问来源于stack exchange,提问作者Rahul
相关产品推荐
相关产品推荐

