Reputation: 8578
Play.classloader.getResourceAsStream(filepath);
filepath - relative to what? project root? playframework root? absolute path?
Or maybe the usage Play.classloader.getResourceAsStream is wrong?
Upvotes: 22
Views: 16412
Reputation: 362
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-
Upvotes: 5
Reputation: 1723
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))
...
}
}
Upvotes: 14
Reputation: 32280
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")
Upvotes: 10
Reputation: 3412
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");
Upvotes: 22
Reputation: 597234
Relative to the classpath root. That is, your WEB-INF/classes
+ all the jars in WEB-INF/lib
Upvotes: -2