Getting a resource file as an InputStream in Playframework

Viewed 15694
Play.classloader.getResourceAsStream(filepath); 

filepath - relative to what? project root? playframework root? absolute path?

Or maybe the usage Play.classloader.getResourceAsStream is wrong?

5 Answers

The accepted answer is deprecated in Play 2.5.x as global access to things like a classloader is slowly being phased out. The recommended way to handling this moving forward is to inject a play.api.Environment then using its classLoader to get the InputStream, e.g.

class Controller @Inject()(env: Environment, ...){

  def readFile = Action {  req =>
    ...

    //if the path is bad, this will return null, so best to wrap in an Option
    val inputStream = Option(env.classLoader.getResourceAsStream(path))

    ...
  }
}
Related