Skip to content

Martini CSV Functions

The Csv class in Martini is designed to facilitate the handling of CSV files in a Groovy context. This class provides a set of functions for reading and processing CSV files efficiently, distinct from the broader Flat File Descriptor service.

Reading CSV Files

Accessing a CSV File

To work with a CSV file, you first need to obtain a reference to the file. This can be achieved by directly creating a File object with the path to your CSV file. For example:

1
File csvFile = new File('/path/to/your/csvfile.csv')

Processing CSV Records

The Csv class includes the eachRecord method to iterate over records in the CSV file. This method can be used in various forms, and one common usage is with a closure to process each record.

The general approach to read and process each record in a CSV file is as follows:

1
2
3
4
5
6
7
8
csvFile.eachRecord { record ->
    // Your code to process each record
    // For example, iterating over each column in the record
    for (int i = 0; i < record.size(); i++) {
        print record[i] + ' '  // Print each column value
    }
    println ''  // Add a new line after each record
}

Practical Example

Here's a practical example demonstrating how to iterate over each record in a CSV file and print its column values:

1
2
3
4
5
6
7
8
File csvFile = new File('/path/to/movies.csv')  // Specify the path to your CSV file

csvFile.eachRecord { record ->
    record.each { column ->
        print column + ' '  // Print each column value
    }
    println ''  // New line after processing each record
}