Lasitha Yapa Lasitha Yapa - 3 months ago 7
Java Question

What is the alternative for Play.application()

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.

Answer

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");    
    }
}