1. Overview

In this tutorial, we’ll learn different approaches to reading a file from the resources folder in Scala. Overall, Scala resources work just the same way as Java resources do.

2. Using getClass.getResource

The first solution we can use comes from Java: the Class.getResource method which returns a URL.

Let’s start by assuming we are following the Java/Scala best practices which recommend putting the resources under src/main/resources. If so, we can get a resource by using the above method:

val resource: URL = getClass.getResource("<my_resource_name>")

And this will return a URL for the resource. Take into account the URL can be null if the resource was not found. There are plenty of methods to read a file from a given URL. If we prefer to work with file paths we can just use URL.getPath.

There’s another variation of the previous solution that’s using the Class.getResourceAsStream that returns an InputStream instead of a URL. This can be especially helpful for lazy load and in case the resource may require a lot of CPU or memory.

3. Using Source

If we are using Scala 2.12 or newer, we can make use of the Source class as well. Source provides us with two different ways of reading resources that we’ll explore.

3.1. Using Source.fromFile

The first possibility is by using the generic Source.fromFile and passing the full resource path:

val file = scala.io.Source.fromFile("src/main/resources/<my_resource>")

But there’s a better way.

3.2. Using Source.fromResource

We can use the dedicated method Source.fromResource to read resources:

val resource = Source.fromResource("<my_resource>")

val lines : Iterator[String] = resource.getLines

And we can easily get the lines of the resource by calling the getLines method.

4. Conclusion

In this article, we saw how we can make use of Java interoperability to read resources in Scala and how to use Scala-specific solutions for that as well.


» 下一篇: ArrayBuffer 指南