How to read files from resources folder in Scala?

I have a folder structure like below:

- main
-- java
-- resources 
-- scalaresources
--- commandFiles 

and in that folders I have my files that I have to read. Here is the code:

def readData(runtype: String, snmphost: String, comstring: String, specificType:  String): Unit = {
  val realOrInvFile = "/commandFiles/snmpcmds." +runtype.trim // these files are under commandFiles folder, which I have to read. 
    try {
      if (specificType.equalsIgnoreCase("Cisco")) {
        val specificDeviceFile: String = "/commandFiles/snmpcmds."+runtype.trim+ ".cisco"
        val realOrInvCmdsList = scala.io.Source.fromFile(realOrInvFile).getLines().toList.filterNot(line => line.startsWith("#")).map{
          //some code 
        }
        val specificCmdsList = scala.io.Source.fromFile(specificDeviceFile).getLines().toList.filterNot(line => line.startsWith("#")).map{
          //some code
        }
      }
    } catch {
      case e: Exception => e.printStackTrace
    }
  }
}

Resources in Scala work exactly as they do in Java. It is best to follow the Java best practices and put all resources in src/main/resources and src/test/resources.

Example folder structure:

testing_styles/
├── build.sbt
├── src
│   └── main
│       ├── resources
│       │   └── readme.txt

Scala 2.12.x && 2.13.x reading a resource

To read resources the object Source provides the method fromResource.

import scala.io.Source
val readmeText : Iterator[String] = Source.fromResource("readme.txt").getLines

reading resources prior 2.12 (still my favourite due to jar compatibility)

To read resources you can use getClass.getResource and getClass.getResourceAsStream .

val stream: InputStream = getClass.getResourceAsStream("/readme.txt")
val lines: Iterator[String] = scala.io.Source.fromInputStream( stream ).getLines

nicer error feedback (2.12.x && 2.13.x)

To avoid undebuggable Java NPEs, consider:

import scala.util.Try
import scala.io.Source
import java.io.FileNotFoundException

object Example {

  def readResourceWithNiceError(resourcePath: String): Try[Iterator[String]] = 
    Try(Source.fromResource(resourcePath).getLines)
      .recover(throw new FileNotFoundException(resourcePath))
 }

good to know

Keep in mind that getResourceAsStream also works fine when the resources are part of a jar, getResource, which returns a URL which is often used to create a file can lead to problems there.

in Production

In production code I suggest to make sure that the source is closed again.


For Scala >= 2.12, use Source.fromResource:

scala.io.Source.fromResource("located_in_resouces.any")

One-liner solution for Scala >= 2.12

val source_html = Source.fromResource("file.html").mkString

import scala.io.Source

object Demo {

  def main(args: Array[String]): Unit = {

    val ipfileStream = getClass.getResourceAsStream("/folder/a-words.txt")
    val readlines = Source.fromInputStream(ipfileStream).getLines
    readlines.foreach(readlines => println(readlines))

  }

}

The required file can be accessed as below from resource folder in scala

val file = scala.io.Source.fromFile(s"src/main/resources/app.config").getLines().mkString