How to use Java.io.PrintWriter Class In Scala
Writing a CSV File
Data will be written to a CSV file using the java.io.PrintWriter class. The data will be written row by row, with each field separated by a comma. The data will be in form of strings and first row will be the header of the data.
Functions:
- new PrintWriter(new File(filename)): Opens or creates a file for writing.
- writer.println(data): Writes a line of data to the file.
Below is the Scala program to write CSV File:
import java.io.PrintWriter
object WriterExample1 {
def main(args: Array[String]): Unit = {
val filename = "outputs.csv"
val writer = new PrintWriter(filename)
writer.println("Name, Age, City")
writer.println("John, 30, New York")
writer.println("Alice, 25, London")
writer.close()
}
}
Explanation:
- Import important libraries: Scala’s java.io.PrintWriter class can be used to write to files.
- Create the CSV file: Use new PrintWriter(new File(“output.csv”)) to open or create a new CSV file.
- Write data to the file: Use println or write methods to write data to the file.
Output:
Reading CSV In Scala
We will read a CSV file using scala.io.Source. The file will be read line by line, and each line will be sperate into fields using the comma.
Functions:
- Source.fromFile(filename): Opens the file for reading.
- file.getLines(): Reads the file line by line.
- line.split(delimiter): Splits each line into fields based on the delimiter.
Below is the Scala program to read a CSV File:
import scala.io.Source
object ReaderExample1 {
def main(args: Array[String]): Unit = {
val filename = "output.csv"
val delimiter = ","
val file = Source.fromFile(filename)
for (line <- file.getLines()) {
val fields = line.split(delimiter).map(_.trim)
println(fields.mkString(", "))
}
file.close()
}
}
Explanation:
- Import the required libraries: In Scala, you can use the scala.io.Source library to read files.
- Open CSV file: Use Source.fromFile(“output.csv”) to open the CSV file.
- Read the data: Split each line using the delimiter and process the data as needed.
Output:
How to Read and Write CSV File in Scala?
Data processing and analysis in Scala mostly require dealing with CSV (Comma Separated Values) files. CSV is a simple file format used to store tabular data, such as a spreadsheet or database. Each line of a CSV file is plain text, representing a data row, with values separated by commas (,). Reading from and writing to CSV files are common tasks across several programming situations. This article focuses on discussing steps to read and write CSV files in Scala.
Table of Content
- Setting Up the Environment
- Using Java.io.PrintWriter Class
- Using Scala-csv Library
- Conclusion
- FAQs
Contact Us