Java USES opencsv to read and write CSV file examples

  • 2020-04-01 03:49:45
  • OfStack

OpenCSV is a simple Java class library for parsing CSV files, which encapsulates the output and reading of CSV format files, can automatically process special characters in CSV format, and the most important is that OpenCSV can be used for commercial-friendly. Specific usage:

Read the CSV file

1. Read in the Iterator mode


CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
    // nextLine[] is an array of values from the line
    System.out.println(nextLine[0] + nextLine[1] + "etc...");
}

2. Use List

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
List myEntries = reader.readAll();

Write a CSV file

1. Similar to FileReader


CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), 't');
// feed in your array (or convert your data to an array)
String[] entries = "first#second#third".split("#");
writer.writeNext(entries);
writer.close();

Custom delimiter

1, custom separator, such as the use of TAB separator


CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), 't');

2. Escape characters can also be used

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), 't', ''');

3. Start with the second (n) line

CSVReader reader = new CSVReader(new FileReader("yourfile.csv"), 't', ''', 2);
dump SQL tables java.sql.ResultSet myResultSet = ....
writer.writeAll(myResultSet, includeHeaders);

To generate Javabeans

ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
strat.setType(YourOrderBean.class);
String[] columns = new String[] {"name", "orderNumber", "id"}; // the fields to bind do in your JavaBean
strat.setColumnMapping(columns);
 
CsvToBean csv = new CsvToBean();
List list = csv.parse(strat, yourReader);

After the


Related articles: