DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Custom Partitioner in Kafka Using Scala: Take Quick Tour!
  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide

Trending

  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • Developers Beware: Slopsquatting and Vibe Coding Can Increase Risk of AI-Powered Attacks
  • Performing and Managing Incremental Backups Using pg_basebackup in PostgreSQL 17
  1. DZone
  2. Coding
  3. Languages
  4. CSV File Writer Using Scala

CSV File Writer Using Scala

Are you looking to generate your own CSV file using Scala? We've got you covered! Learn how to do it, and do it quickly to save you time.

By 
Deepak Mehra user avatar
Deepak Mehra
·
Jan. 19, 17 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
46.3K Views

Join the DZone community and get the full member experience.

Join For Free

The other day, I was looking for a CSV file with some records and started approaching people about it, then I wondered whether I could write my own CSV file, since borrowing it from others is pointless. This actually made me write a piece of code in Scala which generates a CSV file in the specified directory. You can generate your own CSV file with n number of fields and n number of records in it. Also, you can play around with the fields and number of records in the file as and when required.

Creating a Scala Class

Today we're going to make an SBT project.

First, you will need to add a dependency in your build.sbt project:  libraryDependencies += "au.com.bytecode" % "opencsv" % "2.4" 

Now we will write code in our class. In my case, it’s a companion object MakeCSV. You will need to import a few packages in your class.

import java.io.{BufferedWriter, FileWriter}

import scala.collection.JavaConversions._
import scala.collection.mutable.ListBuffer
import scala.util.Random

import au.com.bytecode.opencsv.CSVWriter

Now We Will Start Writing Code In Our Class

  1. val outputFile = new BufferedWriter(new FileWriter("PATH_TO_STORE_FILE/output.csv")): This will create an output file which is an output.csv file in the said directory

  2. val csvWriter = new CSVWriter(outputFile) : this will create a csvwriter object which will have the outputFile in it.

  3. val csvSchema = Array("id", "name", "age", "city") : this is the schema for your CSV file, in my case I have four fields. You can include the schema if you want. It’s totally optional.

  4. val nameList = List("Deepak", "Sangeeta", "Geetika", "Anubhav", "Sahil", "Akshay"): This is the list for the name field.

  5. val ageList = (24 to 26).toList: This is the list for the age
    field.

  6. val cityList = List("Delhi", "Kolkata", "Chennai", "Mumbai"): This is the list for the city field.

  7. val random = new Random(): This is the random object which I have created to take up random items from the list of fields.

  8. var listOfRecords = new ListBuffer[Array[String]](): Here is the list buffer which holds all the records.

  9. listOfRecords += csvFields: This is how we add the fields to our CSV file.

  10. for (i listOfRecords += Array(i.toString, nameList(random.nextInt(nameList.length)), ageList(random.nextInt(ageList.length)).toString, cityList(random.nextInt(cityList.length)))}: Here is the loop which adds records to the listbuffers,here I have used random object to pick up random items from the list of fields.

  11. csvWriter.writeAll(listOfRecords.toList): Here we are writing all the records to the CSV files.

  12. outFile.close(): Here we will finally close the file after writing all the records into it.

The Final Code

import java.io.{BufferedWriter, FileWriter}

import scala.collection.JavaConversions._
import scala.collection.mutable.ListBuffer
import scala.util.Random

import au.com.bytecode.opencsv.CSVWriter

object MakeCSV extends App {

val outputFile = new BufferedWriter(new FileWriter(“/home/deepak/Desktop/deepak19.csv”)) //replace the path with the desired path and filename with the desired filename
val csvWriter = new CSVWriter(outputFile)
val csvFields = Array(“id”, “name”, “age”, “city”)
val nameList = List(“Deepak”, “Sangeeta”, “Geetika”, “Anubhav”, “Sahil”, “Akshay”)
val ageList = (24 to 26).toList
val cityList = List(“Delhi”, “Kolkata”, “Chennai”, “Mumbai”)
val random = new Random()
var listOfRecords = new ListBuffer[Array[String]]()
listOfRecords += csvFields
for (i listOfRecords += Array(i.toString, nameList(random.nextInt(nameList.length))
, ageList(random.nextInt(ageList.length)).toString, cityList(random.nextInt(cityList.length)))
}
csvWriter.writeAll(listOfRecords.toList)
outputFile.close()
}

I have tested the code to make 9 million records in a CSV file. It took 2 minutes and 22 seconds on my machine with an i5 processor and 8 GB RAM. I am gonna come up with a new blog where I will be writing the same code with Spark so that we can test the performance. I really hope the performance will increase when we use Spark.

If you have any challenges, please let me know in the comments. If you enjoyed this post, I’d be very grateful if you’d help it spread. Keep smiling, keep coding!

CSV Scala (programming language) Record (computer science)

Published at DZone with permission of Deepak Mehra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Custom Partitioner in Kafka Using Scala: Take Quick Tour!
  • Mastering Advanced Aggregations in Spark SQL
  • Thermometer Continuation in Scala
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!