how to work with CSV Files
use opencsv library file
( https://mvnrepository.com/artifact/com.opencsv/opencsv)
( https://mvnrepository.com/artifact/com.opencsv/opencsv)
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
public class csv_file {
String sPath=".\\src\\test.csv";
public static void main(String[] args) throws IOException{
csv_file c=new csv_file();
ArrayList<String[]> data=new ArrayList<String[]>(); // Arraylist which stores string array type
String[] a_data={"hi","one"};
String[] a_data2={"this","is","50"};
data.add(a_data);
data.add(a_data2);
c.opencsv_writeAll(data);
System.out.println(c.opencsv_read());
}
public ArrayList<String[]> opencsv_readAll() throws IOException{
CSVReader csv = new CSVReader (new FileReader(sPath));
ArrayList<String[]> data=(ArrayList<String[]>) csv.readAll();
csv.close();
return data;
}
public ArrayList<String[]> opencsv_read() throws IOException{
CSVReader csv= new CSVReader (new FileReader(sPath));
ArrayList<String[]> data=new ArrayList<String[]>();
for(Iterator<String[]> i=csv.iterator();i.hasNext();)
data.add(i.next());
csv.close();
return data;
}
public void opencsv_writeAll(ArrayList<String[]> data) throws IOException{
CSVWriter csv= new CSVWriter (new FileWriter(sPath,true));
csv.writeAll(data);
csv.close();
}
public void opencsv_write(String[] data) throws IOException{
CSVWriter csv= new CSVWriter (new FileWriter(sPath,true));
csv.writeNext(data);
csv.close();
}
}