Java CSV Operations (export and import)
CSV is an acronym for comma-delimited files (Comma separated Values), a plain text format for storing data, typically used in spreadsheets or database software. In a CSV file, the data column is separated by commas, allowing the program to recreate the correct column structure for the data by reading the file, and start a new column each time a comma is encountered.
1. CSV Import/Export wrapper class
Packagecom.parami.utils;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.FileReader;Importjava.io.IOException;ImportJava.io.OutputStreamWriter;Importjava.util.ArrayList;Importjava.util.List;/*** CSV operation (export and import)*/ Public classCsvutils {/*** Export * *@paramFile csv (path + file name), CSV file does not exist automatically created *@paramdataList Data *@return */ Public Static BooleanExportcsv (file file, list<string>dataList) { Booleanissucess=false; FileOutputStream out=NULL; OutputStreamWriter OSW=NULL; BufferedWriter BW=NULL; Try{ out=Newfileoutputstream (file); OSW=NewOutputStreamWriter (out); Bw=NewBufferedWriter (OSW); if(datalist!=NULL&&!Datalist.isempty ()) { for(String data:datalist) {bw.append (data). Append ("\ r"); }} issucess=true; } Catch(Exception e) {issucess=false; }finally{ if(bw!=NULL){ Try{bw.close (); Bw=NULL; } Catch(IOException e) {e.printstacktrace (); } } if(osw!=NULL){ Try{osw.close (); OSW=NULL; } Catch(IOException e) {e.printstacktrace (); } } if(out!=NULL){ Try{out.close (); out=NULL; } Catch(IOException e) {e.printstacktrace (); } } } returnissucess; } /*** Import * *@paramFile CSV files (path + files) *@return */ Public StaticList<string>importcsv (file file) {List<String> datalist=NewArraylist<string>(); BufferedReader BR=NULL; Try{br=NewBufferedReader (Newfilereader (file)); String Line= ""; while(line = Br.readline ())! =NULL) {Datalist.add (line); } }Catch(Exception e) {}finally{ if(br!=NULL){ Try{br.close (); BR=NULL; } Catch(IOException e) {e.printstacktrace (); } } } returndataList; }}
2. CSV Import/Export test
Package Junit.test;import Java.io.file;import java.util.arraylist;import java.util.list;import org.junit.Test; Import com.parami.utils.csvutils;/** * CSV operation (export and import) */public class Csvtest { /** * CSV Export * * @throws Exception * /@Test public void Exportcsv () { list<string> datalist=new arraylist<string > (); Datalist.add ("1, Zhang San, male"); Datalist.add ("2, John Doe, Male"); Datalist.add ("3, Little Red, Female"); Boolean issuccess=csvutils.exportcsv (New File ("D://test.csv"), dataList); System.out.println (issuccess); } /** * CSV Import * * @throws Exception * /@Test public void ImportCSV () { List <String> datalist=csvutils.importcsv (New File ("D://test.csv")); if (Datalist!=null &&!datalist.isempty ()) {for (String data:datalist) { System.out.println (data); } } } }
Java CSV Operations (export and import)