Read and write CSV files in Java

Source: Internet
Author: User

Jar Package Required: Javacsv-2.0.jar

Read operation

//read the contents of a CSV file     Public StaticArraylist<string>readcsv (String filepath) {File csv=NewFile (filepath);//csv file pathCsv.setreadable (true);//Set readableCsv.setwritable (true);//Set writableBufferedReader br =NULL; Try{br=NewBufferedReader (NewFileReader (CSV)); } Catch(FileNotFoundException e) {e.printstacktrace (); } String Line= ""; String Everyline= ""; ArrayList<String> allstring =NewArraylist<>(); Try {             while(line = Br.readline ())! =NULL)//read the content to the line variable{everyline=Line ;                System.out.println (Everyline);            Allstring.add (Everyline); } System.out.println ("All rows in the CSV table:" +allstring.size ()); } Catch(IOException e) {e.printstacktrace (); }        returnallstring; }

Write operations

 Public voidwritecsv (String path) {string Csvfilepath=path;
Try { //Create a CSV write object such as: Csvwriter (file path, delimiter, encoding format);Csvwriter Csvwriter =NewCsvwriter (Csvfilepath, ', ', Charset.forname ("GBK")); //Write ContentString[] headers = {"FileName", "FileSize", "FileMD5"}; Csvwriter.writerecord (headers); for(intI=0;i<writearraylist.size (); i++) {string[] writeLine=writearraylist.get (i). Split (","); System.out.println (WriteLine); Csvwriter.writerecord (WriteLine); } csvwriter.close (); System.out.println ("--------CSV file has been written to--------"); } Catch(IOException e) {e.printstacktrace (); } }

Read and write CSV files in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.