Import Com.univocity.parsers.csv.CsvFormat;
Import Com.univocity.parsers.csv.CsvParser;
Import com.univocity.parsers.csv.CsvParserSettings;
Import Com.univocity.parsers.csv.CsvWriter;
Import com.univocity.parsers.csv.CsvWriterSettings;
To create a CSV file:
public static void Createcsvfile (string[] heads, list<object[]> rows, string outPutPath, string filename)
{
Csvwriter (and all other file writers) work with an instance of
Java.io.Writer
File CSVFile = new file (outPutPath + filename + ". csv");
File parent = Csvfile.getparentfile ();
if (parent! = NULL &&!parent.exists ())
{
Parent.mkdirs ();
}
Try
{
Csvfile.createnewfile ();
Writer fileWriter = new FileWriter (csvfile);
By default, only values of that contain a field separator is enclosed within quotes.
If quotes is part of the value, they is escaped automatically as well. Empty rows are discarded automatically.
Set the field delimiter to '; ', the default value is ', '
Csvwritersettings settings = new Csvwritersettings ();
Csvformat format = Settings.getformat ();
Format.setdelimiter (';');
Csvwriter writer = new Csvwriter (fileWriter, settings);
Write The record headers of this file
Writer.writeheaders (heads);
Write contents and close the given output Writer instance.
Writer.writerowsandclose (rows);
} catch (Exception e)
{
E.printstacktrace ();
Logger.error (e);
}
}
To read a CSV file:
public static list<mytype> Readcsv (String filePath) throws IOException {
list<mytype> eslimports = new arraylist<mytype> ();
File File = new file (FilePath);
InputStream in = new FileInputStream (file);
InputStreamReader reader = new InputStreamReader (in, "UTF-8");
Csvparsersettings settings = new Csvparsersettings ();
Settings.getformat (). Setlineseparator ("\ n");
Csvparser parser = new Csvparser (settings);
Reading data to a list
list<string[]> allrows = Parser.parseall (reader);
Process read-through data
.....
}
Create and read a CSV file using Univocity-parsers