Java操作CSV文件工具类
- 引入Maven依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.3</version>
</dependency>
- CSVUtil
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class CSVUtil {
private CSVUtil() {
}
public static List<List<String>> getData(InputStream stream, String charset) {
try {
List<List<String>> dataList = new ArrayList<>();
Reader reader = new InputStreamReader(stream, charset);
CSVParser parse = CSVFormat.DEFAULT.parse(reader);
List<CSVRecord> records = parse.getRecords();
for (int i = 0; i < records.size(); i++) {
List<String> dataItem = new ArrayList<>();
CSVRecord record = records.get(i);
for (int j = 0; j < record.size(); j++) {
dataItem.add(record.get(j));
}
dataList.add(dataItem);
}
return dataList;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static List<List<String>> getData(String filePath, String charset) {
FileInputStream fin = null;
try {
fin = new FileInputStream(filePath);
return getData(fin, charset);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} finally {
if (fin != null) {
try {
fin.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
public static void saveData(OutputStream os, String charset, List<List<String>> dataList) {
try {
OutputStreamWriter osw = new OutputStreamWriter(os, charset);
CSVPrinter printer = new CSVPrinter(osw, CSVFormat.DEFAULT);
for (List values : dataList) {
printer.printRecord(values);
osw.flush();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static String getStrData(List<List<String>> dataList) {
try {
StringWriter sw = new StringWriter();
CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
for (List<String> values : dataList) {
printer.printRecord(values);
}
return sw.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}