Welcome to this lesson on writing table data to text files using Scala. In today's digital world, efficiently storing and sharing data is crucial. Text files offer a simple and compatible way to handle data across various systems. In this lesson, our goal is to learn how to write formatted table data into a text file using Scala, leveraging the power of the os-lib
library for file operations.
By the end of this lesson, you will be equipped to take structured data and output it to a text file with Scala. Let’s explore this capability and build on what you've previously learned about parsing table and CSV files.
To start, we'll define a Person
case class to serve as the blueprint for our data entries. In this case class, each Person
object will have fields corresponding to the table's columns:
Scala1case class Person(name: String, age: String, occupation: String)
With this structure in place, we can create a list of Person
objects. This list, data
, acts as a collection of rows where each Person
instance represents an individual record:
Scala1val data = List( 2 Person("John", "28", "Engineer"), 3 Person("Alice", "34", "Doctor"), 4 Person("Bob", "23", "Artist") 5)
In this example, we've added three Person
objects to our list, each representing a row with fields for name
, age
, and occupation
. This structured approach simplifies adding or modifying records and facilitates seamless data writing to files.
Now, let's write the data to a text file with tabs as delimiters using Scala's os-lib
. Here's how we can accomplish this:
Scala1// Specify the output file path (text file) 2val outputTxtFilePath = os.pwd / "output.txt" 3 4// Prepare data for tab-separated TXT file 5val txtContent = "Name\tAge\tOccupation\n" + data.map(p => s"${p.name}\t${p.age}\t${p.occupation}").mkString("\n") + "\n" 6 7// Write the content to the TXT file 8os.write.over(outputTxtFilePath, txtContent)
Below is the step-by-step explanation of the code used to write data to a text file in a tab-delimited format:
- Define the Output Path: The file path is set for
output.txt
. - Prepare the Header and Data: The header
Name\tAge\tOccupation
is defined, followed by eachPerson
's data being formatted into tab-separated lines. - Write to File:
os.write.over
writes the content tooutput.txt
, ensuring each entry is on its own line in the file.
In addition to a tab-delimited file, we can also write the data in CSV (Comma-Separated Values) format in Scala. Here's how to do this:
Scala1// Specify the output file path (csv file) 2val outputCsvFilePath = os.pwd / "output.csv" 3 4// Prepare data for comma-separated CSV file 5val csvContent = "Name,Age,Occupation\n" + data.map(p => s"${p.name},${p.age},${p.occupation}").mkString("\n") + "\n" 6 7// Write the content to the CSV file 8os.write.over(outputCsvFilePath, csvContent)
Similarly, this code writes the csvContent
to output.csv
using a comma character as the delimiter, ensuring each record is placed on a new line.
After writing data to the text files, it’s essential to verify that the files contain the correct information. Here's how you can read and print both the tab-delimited and CSV files to ensure their accuracy:
Scala1// Read and print the contents of the tab-delimited TXT file 2val txtFileContent = os.read(outputTxtFilePath) 3println("Tab-delimited file content:") 4println(txtFileContent) 5 6// Read and print the contents of the CSV file 7val csvFileContent = os.read(outputCsvFilePath) 8println("CSV file content:") 9println(csvFileContent)
This step is crucial for ensuring the integrity and accuracy of your file-writing operations. Here's the expected output:
Plain text1Tab-delimited file content: 2Name Age Occupation 3John 28 Engineer 4Alice 34 Doctor 5Bob 23 Artist 6 7CSV file content: 8Name,Age,Occupation 9John,28,Engineer 10Alice,34,Doctor 11Bob,23,Artist
The above output demonstrates the structure and format of the data as stored in each file, allowing you to confirm that the text and CSV files are correctly generated.
Here's how the complete code looks like, from defining the data structure to writing to files and verifying the written data:
Scala1import os._ 2 3case class Person(name: String, age: String, occupation: String) 4 5@main def main() = 6 val data = List( 7 Person("John", "28", "Engineer"), 8 Person("Alice", "34", "Doctor"), 9 Person("Bob", "23", "Artist") 10 ) 11 12 // Tab-delimited text file 13 val outputTxtFilePath = os.pwd / "output.txt" 14 val txtContent = "Name\tAge\tOccupation\n" + data.map(p => s"${p.name}\t${p.age}\t${p.occupation}").mkString("\n") + "\n" 15 os.write.over(outputTxtFilePath, txtContent) 16 17 // CSV file 18 val outputCsvFilePath = os.pwd / "output.csv" 19 val csvContent = "Name,Age,Occupation\n" + data.map(p => s"${p.name},${p.age},${p.occupation}").mkString("\n") + "\n" 20 os.write.over(outputCsvFilePath, csvContent) 21 22 // Verify written data 23 val txtFileContent = os.read(outputTxtFilePath) 24 println("Tab-delimited file content:") 25 println(txtFileContent) 26 27 val csvFileContent = os.read(outputCsvFilePath) 28 println("CSV file content:") 29 println(csvFileContent)
In this lesson, you've learned how to effectively structure, write, and verify data stored in a text file using Scala. We began by organizing data with a case class and a list and then utilized Scala's os-lib
for file operations to output data using tabs and commas as delimiters.
Engage with the practice exercises following this lesson to reinforce your understanding. Experiment with different data structures, adapt them, and ensure your outputs meet expectations. Well done on advancing through this important lesson in Scala.