使用Javacsv.jar的jar包操作csv文件的方法
程序员文章站
2024-03-31 21:27:16
csv其实就是comma separated value的缩写。csv文件是分隔文件,如果使用java的io流来写,比较麻烦,这里为大家提供一个javacsv的jar包,这...
csv其实就是comma separated value的缩写。csv文件是分隔文件,如果使用java的io流来写,比较麻烦,这里为大家提供一个javacsv的jar包,这个很方便操作csv文件。
下载地址:
那如何使用呢?
只要看看以下一个例子,您一下就明白了。
import com.csvreader.csvreader; import com.csvreader.csvwriter; import org.junit.test; import java.io.ioexception; import java.nio.charset.charset; /** * created by javalittleman on 2016/8/18. */ public class testcvs { /** * csv导出 * * @throws exception */ @test public void exportcsv() throws ioexception { string srccsv = "f:/cnt_programa.csv"; string targetfile = "f:/test.csv"; csvreader reader = new csvreader(srccsv, ',', charset.forname("utf-8")); csvwriter write =new csvwriter(targetfile,',',charset.forname("utf-8")); //各字段以引号标记 write.setforcequalifier(true); //路过表头 //r.readheaders(); //逐条读取记录,直至读完 string[] header = {}; while (reader.readrecord()) { //把头保存起来 if (reader.getcurrentrecord()==0){ header = reader.getvalues(); } //获取当前记录位置 system.out.print(reader.getcurrentrecord() + "."); //读取一条记录 system.out.println(reader.getrawrecord()); string[] tmp = {reader.getvalues()[0],reader.getvalues()[1]}; //修改记录,并只写入第一个字段和第二字段 if (!header[1].equals(tmp[1]) && ("".equals(tmp[1])||tmp==null)){ tmp[1]="空"; write.writerecord(tmp); }else{ write.writerecord(new string[]{reader.getvalues()[0],reader.getvalues()[1]}); } } reader.close(); write.close(); } }
cnt_programa.csv文件:
"id","pid","no","serial","name","createtime" "100000","","no100000","","公司新闻","2016/8/23 17:12:09" "100001","","no100001","","热点资讯","2016/8/24 17:12:36" "100046","100001","no100046","1","银行动态","2016/8/1 10:36:31" "100052","100001","no100052","2","法律法规","2016/8/2 20:39:10" "100088","100001","no100088","3","专业文库","2016/8/5 19:05:47"
test.csv
"id","pid" "100000","空" "100001","空" "100046","100001" "100052","100001" "100088","100001"
以上所述是小编给大家介绍的使用javacsv.jar的jar包操作csv文件的方法,希望对大家有所帮助
上一篇: Java实现文件变化监控