<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ittay Stern on Medium]]></title>
        <description><![CDATA[Stories by Ittay Stern on Medium]]></description>
        <link>https://medium.com/@ittays?source=rss-862eb02e9c17------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LhG4DrLKChWhs8QTAiH4Jg.jpeg</url>
            <title>Stories by Ittay Stern on Medium</title>
            <link>https://medium.com/@ittays?source=rss-862eb02e9c17------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 09:51:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ittays/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Jackson CSV Reader/Writer Using Kotlin]]></title>
            <link>https://medium.com/att-israel/jackson-csv-reader-writer-using-kotlin-f37ae771bd6d?source=rss-862eb02e9c17------2</link>
            <guid isPermaLink="false">https://medium.com/p/f37ae771bd6d</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[csv-file]]></category>
            <dc:creator><![CDATA[Ittay Stern]]></dc:creator>
            <pubDate>Wed, 16 Sep 2020 12:41:44 GMT</pubDate>
            <atom:updated>2020-09-16T12:41:44.065Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kiiR5hR0WIrlca0It8kt3A.jpeg" /><figcaption>Image by Pexels from Pixabay</figcaption></figure><p>So you’re writing in Kotlin and you want to load your CSV files to a List, or maybe dump your Collection to a CSV file. This is 100% reasonable, given that CSV files are concise and simple, especially compared to the JSON structure.</p><p>The thing is, that on its face, the CSV format is so simple that it is really tempting to bake your own reader and writer. But instead of trying to convince you that this is going to be a <a href="https://medium.com/@francois.barbanson/5-most-common-parsing-errors-in-csv-files-e6a7e46b9303">rocky</a> <a href="http://thomasburette.com/blog/2014/05/25/so-you-want-to-write-your-own-CSV-code/">road</a>, I want to show you how easy it is to build the whole robust solution with a dozen Kotlin lines, using <a href="https://github.com/FasterXML/jackson">FasterXML’s Jackson</a> modules.</p><p>Did you know that FasterXML has a small <a href="https://github.com/FasterXML/jackson-dataformats-text">collection of data-formats</a> libraries in addition to JSON? As a bonus, all of FasterXML’s great annotations will be in effect to guide our CSV serialization/deserialization rules.</p><p>Eventually the usage will be simple and straight forward. For instance, if Item is your data-class and it matches the CSV file headers, we will read it using:</p><pre>val items: List&lt;Item&gt; = <br>        readCsvFile(&quot;$filesDir/data.csv&quot;)</pre><p>And given that items is a Collection, we will write it as file with:</p><pre>writeCsvFile(items, &quot;$filesDir/data.csv&quot;)</pre><p>We will also be able to read any arbitrary file as a Map, without a known Kotlin type (although the code I’ll show you below will not let us do it the other way around — writing a Map to a file):</p><pre>val data: List&lt;HashMap&lt;String, String&gt;&gt; =<br>        readCsvFile(&quot;$filesDir/data.csv&quot;)</pre><h3>The Dependencies</h3><p>We will add two FasterXML dependencies to our Maven/Gradle dependencies:</p><ol><li>jackson-module-kotlin; see <a href="https://search.maven.org/artifact/com.fasterxml.jackson.module/jackson-module-kotlin">https://search.maven.org/artifact/com.fasterxml.jackson.module/jackson-module-kotlin</a> for the latest version.</li><li>jackson-dataformat-csv; see <a href="https://search.maven.org/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-csv">https://search.maven.org/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-csv</a> for the latest version. Notice that the group-id differs from the first dependency.</li></ol><p>For example, a pom.xml file will be added with these:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7eedbd470e59d84c1356ec6d63c457fc/href">https://medium.com/media/7eedbd470e59d84c1356ec6d63c457fc/href</a></iframe><h3>The Reader</h3><p>For both the reader and the writer, we will use an instance of CsvMapper with a Kotlin module installed. The Kotlin module allows us to seamlessly use Kotlin types.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fb189ada9b38c8ae6e2b2db1a5de9e5/href">https://medium.com/media/8fb189ada9b38c8ae6e2b2db1a5de9e5/href</a></iframe><p>And here is our readCsvFile function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d704558f9cf1cd1d7d9c77ad0ed3671/href">https://medium.com/media/8d704558f9cf1cd1d7d9c77ad0ed3671/href</a></iframe><p>What is going on here? We are opening a file for read and holding it on the reader variable. <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/use.html">The extension function</a><a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/use.html">.use {}</a>is Kotlin’s equivalent to Java’s try-with-resources. It will ensure that our file-handle is properly closed.</p><p>We are chaining .with(CsvSchema.emptySchema().withHeader()) so that the reader will expect the first line on the CSV to be the columns’ names. It will use these to map values into the created objects fields.</p><p>Another interesting part here is the &lt;reified T&gt;, which lets us access the type T that was inferred from the caller’s site. In Java we used to explicitly pass a Class&lt;T&gt; value for this, and Kotlin’s <a href="https://kotlinlang.org/docs/reference/inline-functions.html#reified-type-parameters">reified modifier</a> eliminates this awkwardness. Still, while it leaves our method a lean single-parameter call, it also requires the method to be an inline.</p><h4>Be aware of Huge Files</h4><p>Would you like to handle huge files? The implementation above may not fit your needs because it reads the whole file into memory. Instead you can modify it to return an iterator which streams the file on demand. This is an easy change; in principle it only requires removing the trailing .readAll() and .toList(), as readValues() already returns the desired MappingIterator.</p><h3>The Writer</h3><p>Now for the writeCsvFile function which writes a given collection to a file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5380154aee9fc55e036e65abbfce829a/href">https://medium.com/media/5380154aee9fc55e036e65abbfce829a/href</a></iframe><p>As we did in the readCsvFile method, we use the same csvMapper instance. If you haven’t yet initialized it, see how to do so in the section above.</p><p>Also, as done on the Reader, we use an inline method and a &lt;reified T&gt; so we can easily access the Java class type T::class.<em>java.</em></p><p>With csvMapper.schemaFor(T::class.<em>java</em>).withHeader() we define a writer schema for the Collection’s type T, and also write a headers row on the first line of the CSV file.</p><p>It is not obvious to notice that we have two writers on this method, and both should be closed: the first one is the FileWriter. Its closure is handled by the .use {} function.</p><p>The other writer is Jackson’s SequenceWriter returned by writeValues(). The tailing call to close() closes this writer. This will flush any buffered rows, and more noticeably, will write the headers line to the file in case the input collection has no items.</p><p>This example is easy and useful. Besides its practical benefits, it shows how lean the Kotlin language is. It also demonstrates FasterXML’s Jackson “batteries-included” powers. We just combined both and rolled them on.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f37ae771bd6d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/att-israel/jackson-csv-reader-writer-using-kotlin-f37ae771bd6d">Jackson CSV Reader/Writer Using Kotlin</a> was originally published in <a href="https://medium.com/att-israel">AT&amp;T Israel Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>