Create and read a CSV file using Univocity-parsers

Source: Internet
Author: User

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

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.