Cannot load resource files using Scala / Mill

339 views Asked by At

I cannot load resources in Scala, using Mill (0.10.5) as the build tool.

The minimal example is:

.
├── app
│   └── src
│       └── main
│           ├── resources
│           │   └── hello_world.txt
│           └── scala
│               └── Main.scala
├── build.sc
└── out

with build.sc:

import mill._, scalalib._, mill.modules.Jvm


object app extends ScalaModule {
  def scalaVersion = "2.13.5"
}

and Main.scala:

import scala.io.Source

object Main {
  def main(args: Array[String]): Unit = {
    val helloWorldText : Iterator[String] = Source.fromResource("/hello_world.txt").getLines
    helloWorldText.foreach(println)
  }
}

While mill -i app.run compiles, the program throws an exception:

Exception in thread "main" java.io.FileNotFoundException: resource 'hello_world.txt' was not found in the classpath from the given classloader

What is the right approach to access resource files using Mill?

1

There are 1 answers

3
Tobias Roeser On

Mill ScalaModule does not use the Maven/SBT directory layout by default. Instead, it expects the following directory structure:

.
├── app
│   ├── src
│   |   └── Main.scala
│   └── resources
|       └── hello_world.txt
├── build.sc
└── out

This is also part of the Getting Started section in the documentation.

What you are looking for is a SBT-compatible project layout, which is discussed in the documentation under section SBT-compatible Modules. In short, you need to extend from SbtModule instead of ScalaModule.

Alternatively, you can also override the sources and resources targets, to customize to your needs.