java操作csv檔案之javacsv.jar應用,csvjavacsv.jar

來源:互聯網
上載者:User

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 Exception16      */17     @Test18     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"

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.