How do I find the absolute path to a Play Framework app?
Solution 1
This answer applies only to older versions of the Play Framework, before v2.
Play has an application path property:
String projectRoot = Play.applicationPath;
This will give you the directory that Play is running from.
I think a better practice is moving the directory outside of your project install directory and placing the path to it in your application.conf
as a property. You then retrieve it when needed. For example:
Application.conf:
my.file.path=/tmp/whatever
Code:
String projectRoot = Play.configuration.getProperty("my.file.path");
Solution 2
Since version 2.5.0, play.Play
class is deprecated. It is recommended to inject play.Environment
and use the method as follows:
public File rootPath();
The play.Environment
singleton also contains some very handy method, which provide files by relative path e.g.
public File getFile(String relativePath);
public URL resource(String relativePath);
public InputStream resourceAsStream(String relativePath);
Solution 3
As of play 2.0: play.Play.application().path().getAbsolutePath()
Solution 4
Neither of those worked on my version of play, so I used this instead: Play.current().path().getAbsolutePath()
Admin
Updated on June 07, 2022Comments
-
Admin almost 2 years
At the moment I'm working with a team on a Play! Framework app. With the next user story, I have to implement some different file modifications, such as moving a file to a defined directory.
Because we are working on different platforms, I'm not always really sure if the app has the right path. So I want to work with a absolute path of the app directory.
How do I get the absolute path of a Play! app? Is there a method for this?
-
JDischler almost 11 yearsThis doesn't work on the version of Play I'm using (2.1.1). Looks like the correct way to get the application path is: String path = Play.application().path().getPath();
-
JulienD over 7 yearsCould you please show where and how to inject this Environment ?
-
Tom over 7 years@JulienD, the best way (that may depend on your application requirements and design though) would be to use
play.Environment
in your module. Please look at this example: playframework.com/documentation/2.5.x/… - you can use environment instace while creating your beans / services etc.