hansb hansb - 8 months ago 43
Scala Question

Cannot Use Relative Path in Scala.IO.Source

I am trying to read a CSV file into Scala. I can read fine using the absolute path, but would like to be able to use the relative path.

val filename = "sample_data/yahoo_finance/AAPL/AAPL_Historical.csv"
for (line <- Source.fromFile(filename).getLines()) { println(line) }

throws the error:

java.io.FileNotFoundException: sample_data\yahoo_finance\AAPL\AAPL_Historical.csv
(The system cannot find the path specified)


val filename = "C:/Users/hansb/Desktop/Scala Project/src/main/" +
for (line <- Source.fromFile(filename).getLines()) { println(line) }

works just fine.

My understanding was that scala.io.Source knew to look in the resources folder for the relative path.

What am I missing?

Working code using Phasmid's suggestion:

val relativePath = "/sample_data/yahoo_finance/AAPL/AAPL_Historical.csv"
val csv = getClass.getResource(relativePath)

for (line <- Source.fromURL(csv).getLines()){ println(line) }

Answer Source

This is one of the worst things about Java (and, thus, Scala). I imagine many millions of hours have been spent on this kind of problem.

If you want to get a resource from a relative path (i.e. from the class path) you need to treat the resource as a resource. So, something like the following:


while yields a URL which can then convert into a Stream, or whatever. This form will expect to find the resource in the same (relative) folder as the class, but in the resources rather than scala directory.

If you want to put the resource into the top level of the resources folder, then use:


It may be that there is some other magic which works but I haven't found it.