Apache Commons CSV study: reading files using CSVReader and writing files using CSVPrinter

When I am working on varying projects, I have found that many use the CSV format. I used to write the code to handle the csv files from scratch (they are just specialized text files after all), but I have found that Apache Commons already has the libraries to handle the CSV format. It can be found at http://commons.apache.org/proper/commons-csv/. All we have to do is get it to work.

With that in mind, I have a study of the code necessary to work with the csv library. The code is very ugly and repeats itself several times showing slightly different ways to write the csv file; still, it does show step by step everything you need to do to use it on files.

The CSV file I used to perform this study is located at http://elections.huffingtonpost.com/pollster/2014-alaska-senate-sullivan-vs-begich.csv. I renamed the file “alaska.csv”.

Update 1: code didn’t quite display correctly below due. I recopied the code into the code block correcting the display issues.

Update 2: If you want to download the code, makefiles, and CSV files that I used to create this project, it is available here = FileStudy.zip. It was created in the NetBeans IDE.

Update 3: I updated the title to be a little more descriptive of what the code does. I also recopied the code. As near as I can tell, every time I make a change to the template, the code gets modified. If the code isn’t clean and clear, you might want to download the zip file from Update 2. The zip file contains the actual files I used to create this java study.

package filestudy;

// individual imports for clarity
// this is the CSV package from Apache Commons
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import java.nio.charset.Charset;    // for the csv package
import java.util.ArrayList;         // for storage

// older file access methods since CSV requires them
import java.io.File;                // for CSVParser
import java.io.FileWriter;          // for CSVPrinter
import java.io.IOException;

// I will be using these to check for the existence
// and access rights to the file I want to access.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;

// I want to explore different ways to access the file system.
public class FileStudy {

    // I won't be using command line arguments.
    // All file access will be hard coded for clarity.
    public static void main(String[] args) {
        boolean fileDoesExist, fileDoesNotExist;
        String fileString, outputFileString;
        String outputFileString2, outputFileString3;
        String workingDirectoryString;
        Path pathAndFilename;
        File csvFile = null;
        FileWriter csvFileWriter = null;
        FileWriter csvFileWriter2 = null;
        FileWriter csvFileWriter3 = null;
        
        // should be the path directory where the class was invoked
        workingDirectoryString = System.getProperty("user.dir");
        System.out.println("Class Accessed from: " + workingDirectoryString);
        
        // append a filename to the path
        fileString = "alaska.csv";
        outputFileString = "alaska2.csv";
        outputFileString2 = "alaska3.csv";
        outputFileString3 = "alaska4.csv";
        pathAndFilename = Paths.get(workingDirectoryString, fileString);
        System.out.println("Expected path to file = " + pathAndFilename.toString());
        
        // Check if the file exists
        fileDoesExist = Files.exists(pathAndFilename);
        fileDoesNotExist = Files.notExists(pathAndFilename);
        System.out.println("Exists: " + fileDoesExist);
        System.out.println("Doesn't Exist: " + fileDoesNotExist);
        
        boolean csvFileWasRead = false;
        ArrayList<String[]> arrayList = new ArrayList();
        
        // open the file using older access methods
        // and read its contents into memory
        if(fileDoesExist && !fileDoesNotExist) {
            System.out.println("Accessing file now");
            CSVParser csvFileInput = null;
            int csvRecordValuesCount;
            String[] csvValueStorage;
            try {
                csvFile = new File(pathAndFilename.toString());
                csvFileInput = CSVParser.parse(
                                            csvFile,
                                            Charset.defaultCharset(),
                                            CSVFormat.DEFAULT);
               for(CSVRecord csvRecord : csvFileInput) {
                   System.out.println("Loading record # "
                           + csvFileInput.getRecordNumber());
                   csvRecordValuesCount = csvRecord.size();
                   csvValueStorage = new String[csvRecordValuesCount];
                   for(int x = 0; x < csvRecordValuesCount; x++) {
                       csvValueStorage[x] = csvRecord.get(x);
                   }
                   arrayList.add(csvValueStorage);
               }
               csvFileWasRead = true;
            } catch(IOException ioException) {
                System.out.println("IOException: " + ioException.getMessage());
            } catch(NullPointerException nullException) {
                System.out.println("Null Pointer Exception: " + nullException.getMessage());
            } finally {
                if(csvFileInput != null && !csvFileInput.isClosed()) {
                    try {
                    System.out.println("Closing csvFileInput");
                    csvFileInput.close();
                    } catch(IOException io) {
                        System.out.println("Complete File Failure: " + io.getMessage());
                        System.exit(1);
                    }
                } else {
                    System.out.println("I found nothing to close");
                }
            }
        }
        
        // if the read was successful, make a copy one value at a time
        if(csvFileWasRead) {
            int arrayLength = arrayList.size();
            int recordLength;
            String[] stringArrayToWrite;
            CSVPrinter csvPrinter = null;
            pathAndFilename = Paths.get(workingDirectoryString, outputFileString);
            try {
                System.out.println("Creating FileWriter");
                csvFileWriter = new FileWriter(pathAndFilename.toString());
                System.out.println("Creating CSVPrinter");
                csvPrinter = new CSVPrinter(csvFileWriter, CSVFormat.DEFAULT);
                for(int x = 0; x < arrayLength; x++) {
                    stringArrayToWrite = arrayList.get(x);
                    recordLength = stringArrayToWrite.length;
                    for(int y = 0; y < recordLength; y++) {
                        csvPrinter.print(stringArrayToWrite[y]);
                    }
                    csvPrinter.println();
                    System.out.println("Finished printing record # " + (x+1) + " at location " + x);
                }
            } catch(IOException writingError) {
                System.out.println("Error in writing: " + writingError.getMessage());
            } finally {
                if(csvPrinter != null) {
                    try {
                        System.out.println("Closing csvPrinter");
                        csvPrinter.close();
                    } catch(IOException closingError) {
                        System.out.println("Unable to close csvFileWriter: "
                                + closingError.getMessage());
                    }
                }
            }
        }

        // if the read was successful, make a
        // second copy using a different techinque
        if(csvFileWasRead) {
            int arrayLength = arrayList.size();
            String[] stringArrayToWrite;
            CSVPrinter csvPrinter = null;
            pathAndFilename = Paths.get(workingDirectoryString, outputFileString2);
            try {
                System.out.println("Creating FileWriter2");
                csvFileWriter2 = new FileWriter(pathAndFilename.toString());
                System.out.println("Creating CSVPrinter");
                csvPrinter = new CSVPrinter(csvFileWriter2, CSVFormat.DEFAULT);
                for(int x = 0; x < arrayLength; x++) {
                    stringArrayToWrite = arrayList.get(x);
                    csvPrinter.printRecord((Object[])stringArrayToWrite);
                }
            } catch(IOException writingError) {
                System.out.println("Error in writing: " + writingError.getMessage());
            } finally {
                if(csvPrinter != null) {
                    try {
                        System.out.println("Closing csvPrinter");
                        csvPrinter.close();
                    } catch(IOException closingError) {
                        System.out.println("Unable to close csvFileWriter: "
                                + closingError.getMessage());
                    }
                }
            }
        }
        
        // if the read was successful, make a
        // third copy using a different techinque
        if(csvFileWasRead) {
            CSVPrinter csvPrinter = null;
            pathAndFilename = Paths.get(workingDirectoryString, outputFileString3);
            try {
                System.out.println("Creating FileWriter3");
                csvFileWriter3 = new FileWriter(pathAndFilename.toString());
                System.out.println("Creating CSVPrinter");
                csvPrinter = new CSVPrinter(csvFileWriter3, CSVFormat.DEFAULT);
                csvPrinter.printRecords(arrayList);
            } catch(IOException writingError) {
                System.out.println("Error in writing: " + writingError.getMessage());
            } finally {
                if(csvPrinter != null) {
                    try {
                        System.out.println("Closing csvPrinter");
                        csvPrinter.close();
                    } catch(IOException closingError) {
                        System.out.println("Unable to close csvFileWriter: "
                                + closingError.getMessage());
                    }
                }
            }
        }
    }
    
}

Advertisements

Published by

Marisa

I am a writer of words, a thinker of thoughts, a changer of genders, and a queerer of life. I am an antagonist of the ordinary; and while I do tolerate it, I also look at it with contempt.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s