FileInputStream fis = null;
                BOMInputStream bomIn = null;
                InputStreamReader inputStreamReader = null;
                try {

                    File csvFile = new File(filePath);
                    fis = new FileInputStream(csvFile);
                    //可检测多种类型,并剔除bom
                    bomIn = 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();
                        }
                    }
                }

  

posted on 2025-12-23 13:38  默西塞德  阅读(1)  评论(0)    收藏  举报