CSV is actually the abbreviation of COMMA SEPARATED VALUE. The csv file is a delimited file. If you use java io stream to write, it is more troublesome. Here we provide you with a javacsv jar package, which is very convenient for operating the csv file.
Download address: http://xiazai.VeVB.COM/201608/yuanma/javcsv(VeVB.COM).rar
So how to use it?
Just look at the following example and you will understand immediately.
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 export** @throws Exception*/@Testpublic 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"));//Each fields are marked with quotes write.setForceQualifier(true);//Passing the header//r.readHeaders();//Read records one by one until String[] header = {}; while (reader.readRecord()) {//Save the header if (reader.getCurrentRecord()==0){header = reader.getValues();}//Get the current record location System.out.print(reader.getCurrentRecord() + ".");//Read a record System.out.println(reader.getRawRecord());String[] tmp = {reader.getValues()[0],reader.getValues()[1]};//Modify the record and write only the first and second fields if (!header[1].equals(tmp[1]) && ("".equals(tmp[1])||tmp==null)){tmp[1]="null";write.writeRecord(tmp);}else{write.writeRecord(new String[]{reader.getValues()[0],reader.getValues()[1]});}}reader.close();write.close();}}cnt_programa.csv file:
"id","pid","no","serial","name","createtime"1000000","","No100000","","Company News","2016/8/23 17:12:09""100001","","No100001","","Hot News","2016/8/24 17:12:36""100046","100001","No100046","1","Bank News","2016/8/1 10:36:31""100052","100001","No100052","2","Legal Regulations","2016/8/2 20:39:10""100088","100001","No100088","3","Professional Library","2016/8/5 19:05:47"
test.csv
"id","pid""100000","empty""100001","empty""100046","100001""100052","100001""100088","100001"
The above is the method of using the Javacsv.jar jar package to operate csv files. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!