使用Javacsv.jar的jar包操作csv文件的方法
作者:爪哇小汉
使用javacsv的jar包很方便的可以操作csv文件。下面通过本教程给大家介绍使用javacsv.jar操作csv文件的方法,感兴趣的朋友一起看下吧
CSV其实就是COMMA SEPARATED VALUE的缩写。csv文件是分隔文件,如果使用java的io流来写,比较麻烦,这里为大家提供一个javacsv的jar包,这个很方便操作csv文件。
下载地址:http://xiazai.jb51.net/201608/yuanma/javcsv(jb51.net).rar
那如何使用呢?
只要看看以下一个例子,您一下就明白了。
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文件的方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!