Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play2, Scala: Loading resources does not work in production mode

In a controller class, I need to load a text file. I put this file in the public folder and wrote an object, that provides this text file as a string.

object FooResources {
  def load(filePath: String): String = {
    Play.getExistingFile(filePath) match {
      case Some(file) => Files.readFile(file)
      case _ => throw new IOException("file not found: " + filePath)
    }
  }
}

In the controller class I just call:

val js = FooResources.jsTemplate("public/jsTemplate.js").

This is working fine in DEV mode, but when I stage the project via play clean compile stage and starting via ./start, then I get Exceptions when trying to load the file.

UPDATE: When I start the project from within sbt (or play) via start command, then the file is successfully loaded. Only when I start the app via ./start in the target directory, it's not.

like image 359
schub Avatar asked Dec 12 '25 12:12

schub


1 Answers

When you use the dist or stage target, your ressources are included within a Jar file, instead on the filesystem.

So you have to use an inputstream relative to your classpath. For this, take a look at the Play.api.resourceAsStream() method in the Play object.

Maybe something like this (did not test it)

object FooResources {
  def load(filePath: String): InputStream = {
    Play.resourceAsStream(filePath) match {
      case Some(is) => scala.io.Source.fromInputStream(is).getLines().mkString("\n")
      case _ => throw new IOException("file not found: " + filePath)
    }
  }
}
like image 64
ndeverge Avatar answered Dec 16 '25 02:12

ndeverge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!