CSV文件本身是一个文本文件,可以通过记事本打开,是根据“,”来进行分割数据的。因此,如果想要读取一个csv文件,可以通过流的形式来完成。
下面是获取CSV文件并将其转化为List<String[]>集合的方法。
/**
* 获取csv格式文件的内容
*
* @param multipartFile
* @return 以list<String [ ]>形式返回
* @throws IOException
*/
public List<String[]> getCSVList(MultipartFile multipartFile) throws IOException {
InputStream inputStream = multipartFile.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//第一行信息,为标题信息,不需要,如果需要,请注释
reader.readLine();
String line = null;
List<String[]> arrayList = new ArrayList<>();
while ((line = reader.readLine()) != null) {
String[] item = line.split(",");
//对于空白行,不需要获取
if (item.length != 1) {
arrayList.add(item);
}
}
return arrayList;
}