/** * 解析csv文件并转成bean * @param file csv文件 * @param clazz 类 * @param <T> 泛型 * @return 泛型bean集合 */ public static <T> List<T> getCsvData(MultipartFile file, Class<T> clazz) { InputStreamReader inputStreamReader = null; try { InputStream inputStream = getInputStream(file.getInputStream()); inputStreamReader = new InputStreamReader(inputStream, "utf-8"); } catch (Exception e) { e.printStackTrace(); } HeaderColumnNameMappingStrategy<T> strategy = new HeaderColumnNameMappingStrategy<>(); strategy.setType(clazz); CsvToBean<T> csvToBean = new CsvToBeanBuilder<T>(inputStreamReader) .withSeparator(',') .withQuoteChar('\'') .withMappingStrategy(strategy).build(); return csvToBean.parse(); }
/** * 读取流中前面的字符,看是否有bom,如果有bom,将bom头先读掉丢弃 * * @param in * @return * @throws IOException */ public static InputStream getInputStream(InputStream in) throws IOException { PushbackInputStream testin = new PushbackInputStream(in); int ch = testin.read(); if (ch != 0xEF) { testin.unread(ch); } else if ((ch = testin.read()) != 0xBB) { testin.unread(ch); testin.unread(0xef); } else if ((ch = testin.read()) != 0xBF) { throw new IOException("错误的UTF-8格式文件"); } else { } return testin; }