首页 > 代码库 > java 读写csv
java 读写csv
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>
java 读写csv
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。