How to read a file in Play Framework 2.2.1?

randombits picture randombits · Feb 20, 2014 · Viewed 10.6k times · Source

I have a static file that I want to read in one of my Play Framework models. The file contains some simple text in it. I can't find any examples or API that shows where the appropriate location is to store such a resource and second, how to access that resource. For whatever it is worth I'm using Play for Scala, but I don't think that's relevant here.

Answer

Carsten picture Carsten · Feb 21, 2014

There is no real designated location where data files should go. I usually set a path in my application.conf and then read it in the application via

Play.application().configuration.getString("my.data.path")

If you want to store it somewhere inside your Play application's directory, you can get its root path via

Play.application().path()

which returns a java.io.File.

For reading files, there is no Play-specific technique. This question has been asked and answered before. In short, to read a small text file, just do this:

val lines = scala.io.Source.fromFile("file.txt").mkString