Write a CSV File as a Text Table

This example shows how to write records as a plain-text table that is easy to read in a terminal, a log or an e-mail. A TextTableWriter writes a header row of field names, a dashed separator and one padded, aligned row per record. The columns are the union of the field names across all records in first-seen order, and rows leave a blank cell where a record has no value for a column.

Because the column widths depend on every value, the writer buffers the records in memory and writes the table when it closes. The default separator between columns is two spaces; this example replaces it with | .

Input CSV file

Account,LastName,FirstName,Balance,CreditLimit,AccountCreated,Rating
101,Reeves,Keanu,9315.45,10000.00,1/17/1998,A
312,Butler,Gerard,90.00,1000.00,8/6/2003,B
868,Hewitt,Jennifer Love,0,17000.00,5/25/1985,B
761,Pinkett-Smith,Jada,49654.87,100000.00,12/5/2006,A
317,Murray,Bill,789.65,5000.00,2/5/2007,C

Java Code Listing

package com.northconcepts.datapipeline.examples.cookbook;

import java.io.File;

import com.northconcepts.datapipeline.core.DataReader;
import com.northconcepts.datapipeline.core.DataWriter;
import com.northconcepts.datapipeline.csv.CSVReader;
import com.northconcepts.datapipeline.job.Job;
import com.northconcepts.datapipeline.texttable.TextTableWriter;

public class WriteACsvFileAsATextTable {

    public static void main(String[] args) {
        DataReader reader = new CSVReader(new File("example/data/input/credit-balance-01.csv"))
                .setFieldNamesInFirstRow(true);

        DataWriter writer = new TextTableWriter(new File("example/data/output/credit-balance-01.txt"))
                .setColumnSeparator(" | ");

        Job.run(reader, writer);
    }

}

Code Walkthrough

  1. A CSVReader reads credit-balance-01.csv with field names in the first row.
  2. A TextTableWriter is created for the output file example/data/output/credit-balance-01.txt; setColumnSeparator(" | ") replaces the default two-space separator. A constructor that takes a Writer is also available.
  3. Job.run() transfers the records into the writer's buffer and closes it, which computes the column widths and writes the table.

Output text file

Account | LastName      | FirstName     | Balance  | CreditLimit | AccountCreated | Rating
------- | ------------- | ------------- | -------- | ----------- | -------------- | ------
101     | Reeves        | Keanu         | 9315.45  | 10000.00    | 1/17/1998      | A
312     | Butler        | Gerard        | 90.00    | 1000.00     | 8/6/2003       | B
868     | Hewitt        | Jennifer Love | 0        | 17000.00    | 5/25/1985      | B
761     | Pinkett-Smith | Jada          | 49654.87 | 100000.00   | 12/5/2006      | A
317     | Murray        | Bill          | 789.65   | 5000.00     | 2/5/2007       | C
Mobile Analytics