Kan011
Kan011

Reputation: 11

Read text file in scala command Line

I am trying to read a text file via scala command line. The code compiles correctly, but it fails on execution due to file not found error.

import scala.io.Source

object Mainclass extends App {
    val filename = "filo.txt"
    for(line <- Source.fromFile(filename).getLines) {
      println(line)
    }
}

This is the error:

scala Main.scala:
java.io.FileNotFoundException: filo.txt (The system cannot find the file specified)

Upvotes: 1

Views: 688

Answers (1)

Ben McNiel
Ben McNiel

Reputation: 8801

Since filo.txt is a relative file path you need to make sure that the running program uses the location of filo.txt as the working directory.

Example:

echo 'my test data' > ~/mydir/filo.txt
cd ~/mydir
scala Main.scala

So when you run this program it needs to be started in mydir. You could avoid this by using a fully qualified path.

Upvotes: 2

Related Questions