程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA綜合教程 >> java操作csv文件之javacsv.jar應用,csvjavacsv.jar

java操作csv文件之javacsv.jar應用,csvjavacsv.jar

編輯:JAVA綜合教程

java操作csv文件之javacsv.jar應用,csvjavacsv.jar


csv文件是分隔文件,如果使用java的io流來寫,比較麻煩,這裡為大家提供一個javacsv的jar包,這個很方便操作csv文件。

下載地址:https://pan.baidu.com/s/1i46ErFB

那如何使用呢?

只要看看以下一個例子,您一下就明白了。

 

 1 import com.csvreader.CsvReader;
 2 import com.csvreader.CsvWriter;
 3 import org.junit.Test;
 4 
 5 import java.io.IOException;
 6 import java.nio.charset.Charset;
 7 
 8 /**
 9  * Created by javalittleman on 2016/8/18.
10  */
11 public class TestCVS {
12     /**
13      * CSV導出
14      *
15      * @throws Exception
16      */
17     @Test
18     public void exportCsv() throws IOException {
19         String srcCSV = "F:/cnt_programa.csv";
20         String targetFile = "F:/test.csv";
21         CsvReader reader = new CsvReader(srcCSV, ',', Charset.forName("UTF-8"));
22         CsvWriter write =new CsvWriter(targetFile,',',Charset.forName("UTF-8"));
23         //各字段以引號標記
24         write.setForceQualifier(true);
25         //路過表頭
26         //r.readHeaders();
27         //逐條讀取記錄,直至讀完
28         String[] header = {};
29         while (reader.readRecord()) {
30             //把頭保存起來
31             if (reader.getCurrentRecord()==0){
32                 header = reader.getValues();
33             }
34             //獲取當前記錄位置
35             System.out.print(reader.getCurrentRecord() + ".");
36             //讀取一條記錄
37             System.out.println(reader.getRawRecord());
38             String[] tmp = {reader.getValues()[0],reader.getValues()[1]};
39             //修改記錄,並只寫入第一個字段和第二字段
40             if (!header[1].equals(tmp[1]) && ("".equals(tmp[1])||tmp==null)){
41                 tmp[1]="空";
42                 write.writeRecord(tmp);
43             }else{
44                 write.writeRecord(new String[]{reader.getValues()[0],reader.getValues()[1]});
45             }
46         }
47         reader.close();
48         write.close();
49     }
50 }

 

 

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"

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved