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.
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)
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With