Write a CSV File to Fixed Width

Updated: Jun 1, 2023

This example shows you how to write the contents of a CSV file to a Fixed Width file in Java using the CSVReader and FixedWidthWriter classes.

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

/*
 * Copyright (c) 2006-2022 North Concepts Inc.  All rights reserved.
 * Proprietary and Confidential.  Use is subject to license terms.
 * 
 * https://northconcepts.com/data-pipeline/licensing/
 */
package com.northconcepts.datapipeline.examples.cookbook;

import java.io.File;

import com.northconcepts.datapipeline.core.DataReader;
import com.northconcepts.datapipeline.csv.CSVReader;
import com.northconcepts.datapipeline.fixedwidth.FixedWidthWriter;
import com.northconcepts.datapipeline.job.Job;

public class WriteACsvFileToFixedWidth {
    
    public static void main(String[] args) throws Throwable {
        DataReader reader = new CSVReader(new File("example/data/input/credit-balance-01.csv"))
            .setFieldNamesInFirstRow(true);
        
        FixedWidthWriter writer = new  FixedWidthWriter(new File("example/data/output/credit-balance-02.fw"));
        writer.addFields(8);
        writer.addFields(16);
        writer.addFields(16);
        writer.addFields(12);
        writer.addFields(14);
        writer.addFields(16);
        writer.addFields(7);
        
        Job.run(reader, writer);
    }

}

Code Walkthrough

  1. A CSVReader is created corresponding to the input CSV file credit-balance-01.csv.
  2. A FixedWidthWriter is created corresponding to the output Fixed Width file i.e. credit-balance-02.fw.
  3. The writer.addField(s) method is invoked for the fields that need to be written to the output file.
  4. Data is transferred from the input CSV file to the output Fixed Width file via the JobTemplate.DEFAULT.transfer method.

Output Fixed Width 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