import java.io.IOException; import java.nio.charset.Charset; import com.csvreader.CsvReader; import com.csvreader.CsvWriter; public class CsvUtil { /** * 读取CSV文件 * @throws Exception */ public static void readeCsv() throws Exception{ CsvReader r = new CsvReader("d:/test2.csv", ',',Charset.forName("GBK")); //读取表头 while(r.readHeaders()){ System.out.println(r.getRawRecord()); } //逐条读取记录,直至读完 while (r.readRecord()) { //读取一条记录 System.out.println(r.getRawRecord()); //按列名读取这条记录的值 System.out.println(r.get("Name")); System.out.println(r.get("class")); System.out.println(r.get("number")); System.out.println(r.get("sex")); } r.close();} /** * 写入CSV文件 */ public static void writeCsv(){ try { String csvFilePath = "d:/test2.csv"; CsvWriter wr =new CsvWriter(csvFilePath, ',',Charset.forName("GBK")); // String[] contents = {"aaaaa","bbbbb","cccccc","ddddddddd"}; String[] contents = {"Lilymm","五一","90","女"}; String[] contents2 = {"Lilyo","五一","90","女"}; wr.writeRecord(contents); wr.writeRecord(contents2); wr.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { writeCsv(); try { readeCsv(); } catch (Exception e) { e.printStackTrace(); } } }
<dependency> <groupId>net.sourceforge.javacsv</groupId> <artifactId>javacsv</artifactId> <version>2.0</version> </dependency>