2
votes

I am new to Play framework. I wanted to read a file which is in the conf folder. So I used

Play.application().classloader().getResources("Data.json").nextElement().getFile()

But I got to know that play.Play is deprecated now. What can I use to read the file. I read this article and can hardly understand what it says.

4
which version are you using? You have tagged the post with v2.3 but play.Play was deprecated in 2.5jacks
@Nio Thank u very much. I corrected it. I am using 2.5Lasitha Yapa

4 Answers

3
votes

Just inject the Application in the class where you need it. Supposing it is in a controller:

import play.Application;
import javax.inject.Inject;
import javax.inject.Provider;

class YourController extends Controller {

    @Inject
    Provider<Application> app;


    public Result someMethod() {
        // (...)
        // File is placed in conf/Data.json
        InputStrem is = app.get().classloader().getResourceAsStream("Data.json");
        String json = new BufferedReader(new InputStreamReader(is))
                .lines().collect(Collectors.joining("\n")); 
        return ok(json).as("application/json");    
    }
}
1
votes

The 2.5 migration article you read focuses on Play's migration from Global state to Dependency Injection as a means to wire dependencies - hence the removal of those static methods. If you don't really understand this yet, then do not worry.

Assuming this configuration entry (either in application.conf or another file imported into application .conf:-

my_conf_key = "some value"

Here is an example of looking up the configuration property using 2.5:-

import play.api._
import play.api.mvc._
import javax.inject.Inject

class TestConf @Inject() (conf: Configuration) extends Controller {

  def config = Action {
    Ok(conf.underlying.getString("my_conf_key"))
  }

}

prints:-

some value
1
votes

Salem gave you an example for a specific use-case. In this post you can find more detailed explanation of dependency injection in Play.

And this post is about migration to Play 2.5.

I hope this will help you.

0
votes

Injecting Application didn't work, so I had to inject Environment and then call environment.resource("resource.xsd");

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("data.xsd");
          // Do what you want with the stream here
     }

     public void readResource(){
          URL resource = environment.resource("data.xsd");
     }
}

Play Documentation about Application interface: https://www.playframework.com/documentation/2.6.9/api/java/play/Application.html