Play.classloader.getResourceAsStream(filepath);
filepath - relative to what? project root? playframework root? absolute path?
Or maybe the usage Play.classloader.getResourceAsStream is wrong?
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")
Inject Environment
and then call environment.resourceAsStream("filename");
Example:
import javax.inject.Inject;
public class ExampleResource extends Controller{
private final Environment environment;
@Inject
public ExampleResource(Environment environment){
this.environment = environment;
}
public void readResourceAsStream() {
InputStream resource = environment.resourceAsStream("filename");
// Do what you want with the stream here
}
}
Documentation: https://www.playframework.com/documentation/2.8.0/api/java/play/Environment.html#resourceAsStream-java.lang.String-
Relative to the classpath root. That is, your WEB-INF/classes
+ all the jars in WEB-INF/lib