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