Small steps to Scala (8/20) - files and regex

Scala
8/20

Files and Regex

  • reading lines
  • reading characters
  • reading tokens
  • reading different sources
  • writing files
  • reading directories
  • system call
  • regular expressions

Reading lines

In order to read a file we need to import Source from the scala.io package. Let's import a file and read the first 5 lines.

import scala.io.{Source => src}

val f = "/path/to/file"
val s = src.fromFile(f, "UTF-8")

val lines = s.getLines  // the type of lines is Iterator[String]

lines.take(5).foreach { line => println(line) }

Reading characters

For character reading also we need to import Source. Assuming you already have it imported, let's print the first 10 characters.

val s = src.fromFile(f, "UTF-8")
val chars = s.buffered

chars.take(10).foreach(print)

Reading space separated words

After we read from a file, we can put the contents into a single string.

val s = src.fromFile(f, "UTF-8")
val contents = s.mkString.split("\\s+")

contents.take(5).foreach(println)

The above code will print 5 words each on its own line.

Reading different sources

Below is a sample code on how to read from a URL, from a string and from standard input.

import scala.io.{Source => src}

val s = src.fromURL("https://www.example.com/", "UTF-8")
val s = src.fromString("Hello Scala!")
val s = src.stdin

In order to read binary files, Scala uses Java libraries.

import java.io.{File, FileInputStream}

val file = new File(f)
val in = new FileInputStream(f)
val bytes = new Array[Byte](f.length.toInt)
in.read(bytes)
in.close()

Writing files

We've been reading from files, now it's time to do some writing also. Again we will use Java libraries for that. Let's write the letters from A to Z to a file.

import java.io.PrintWriter

val f = "/path/to/file"
val out = new PrintWriter(f)

'A' to 'Z' foreach(out.println)
out.close()

Reading directories

Unfortunately, Scala doesn't have its own way of reading directories, so we will have to make our own function.

import java.io.File

def subdirs(dir: String): Array[String] = {
  (new File(dir)).listFiles.filter(_.isDirectory).map(_.getName)
}

val path = "/path/to/read"

subdirs(path).foreach(println)

We can also print the folders in the path like this:

for(d <- subdirs(path)) println(d)

System call

You perform a system call from the Scala shell. The ! operator will execute the command and !! will return the result as a string.


import sys.process._

"ls -ltr /path/to/some/directory/" !

val result = "ls" !!  // this variable is of type String
  • pipe commands using the #| operator.
"ls -l ." #| "grep txt" !
  • redirect output to file with #> operator
"cat file.txt" #| "grep -c key" #> new File("output.txt") !
  • append content to output with #>> operator
"ls -al ." #>> new File("output.txt") !
  • input from file with #< operator
"grep scala" #< new File("input.txt") !
  • input from URL and return a string
"grep scala" #< new URL("http://www.example.com") !!
  • execute process p if q is successful using #&& operator
p #&& q !
  • execute process p is q is NOT successful using #|| operator
p #|| q !

Regular expressions

To construct a regex object all you need to do is to use the r method:

val pattern = "[0-9]+".r

val matches = pattern.findAllIn("This article is called 'Small steps to Scala (8/20) - Files and regex'").toArray

The above code will return Array(8, 20).


[+] Scala series
  • Small steps to Scala 1/20 - the basics
  • Small steps to Scala 2/20 - functions
  • Small steps to Scala 3/20 - arrays
  • Small steps to Scala 4/20 - maps and tuples
  • Small steps to Scala 5/20- classes
  • Small steps to Scala 6/20 - objects
  • Small steps to Scala 7/20 - inheritance

  • Disclaimer: This is by no means an original work it is merely meant to serve as a compilation of thoughts, code snippets and teachings from different sources.