Play.classloader.getResourceAsStream(filepath);
filepath - relative to what? project root? playframework root? absolute path?
Or maybe the usage Play.classloader.getResourceAsStream is wrong?
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");
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))
...
}
}
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")
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