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.

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)
    }
  }
}

Need Your Help

Make portable these P/Invoke calls

.net vb.net winforms winapi pinvoke

I'm developoing an AnyCPU application and I'm doing some calls to CallNextHookEx and SetWindowsHookEx functions, but the VisualStudio code analysis throws me a P/Invoke declarations should be porta...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.