ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

使用org.apache.commons的CSVParser 处理bom问题

2026/9/23 9:02:03 拓冰建站 浏览量
使用org.apache.commons的CSVParser 处理bom问题
                FileInputStream fis = null;BOMInputStream bomIn = null;InputStreamReader inputStreamReader = null;try {File csvFile = new File(filePath);fis = new FileInputStream(csvFile);//可检测多种类型,并剔除bombomIn = new BOMInputStream(fis, false, ByteOrderMark.UTF_8, ByteOrderMark.UTF_16LE, ByteOrderMark.UTF_16BE);String charset = "utf-8";//若检测到bom,则使用bom对应的编码if (bomIn.hasBOM()) {charset = bomIn.getBOMCharsetName();}inputStreamReader = new InputStreamReader(bomIn, charset); CSVParser csvParser = new CSVParser(inputStreamReader, CSVFormat.DEFAULT.withFirstRecordAsHeader().withIgnoreSurroundingSpaces());                  } catch (IOException e) {e.printStackTrace();} finally {if (inputStreamReader != null) {try {inputStreamReader.close();} catch (IOException e) {e.printStackTrace();}}if (bomIn != null) {try {bomIn.close();} catch (IOException e) {e.printStackTrace();}}if (fis != null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}}