Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a resource file as an InputStream in Playframework

Play.classloader.getResourceAsStream(filepath); 

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

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

like image 333
bArmageddon Avatar asked Jul 31 '11 08:07

bArmageddon


3 Answers

In the Play Framework the "conf" directory is on the classpath, so you can put your file there and open it with getResourceAsStream.

For example if you create a file "conf/foo.txt" you can open it using

Play.classloader.getResourceAsStream("foo.txt");
like image 116
Eamonn O'Brien-Strain Avatar answered Oct 21 '22 18:10

Eamonn O'Brien-Strain


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

    ...
  }
}
like image 27
josephpconley Avatar answered Oct 21 '22 19:10

josephpconley


As an alternative to using the conf dir (which should only be used for configuration-related files), you can use the public dir and access it with:

 Play.classloader.getResourceAsStream("public/foo.txt")

Or in Scala with:

 Play.resourceAsStream("public/foo.txt")
like image 10
cdmckay Avatar answered Oct 21 '22 18:10

cdmckay