How to read a file in Play Framework 2.2.1?

I have a static file that I want to read in one of my Play Framework models. The file contains plain text. I can’t find examples or APIs that show where the corresponding storage location is for such a resource, and secondly, how to access this resource. Whatever it costs, I use Play for Scala, but I don't think it is relevant here.

+5
source share
3 answers

You can put any resource file in the / conf folder and download it (programmatically) as described here: Custom configuration files - Play! Framework 2.0

+3
source

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

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

If you want to save it somewhere in the directory of the Play application, you can get its root path through

 Play.application().path() 

which returns java.io.File .

There is no specific playback technique for reading files. This question has been asked and answered before . In short, to read a small text file, simply do the following:

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

I answered a similar question at fooobar.com/questions/1004889 / .... I think the same answer will be applied to you.

You can choose the location that you prefer rather than in dedicated folders for specific tasks. For example, you can create the / resources folder. Do not create a resource folder inside the folder / application, as this is only a place to store code. The same thing happens with other specific folders. Then you can use

 import import play.Play; Play.application().getFile("relative_path_from_<Project_Root>); 

to access the file inside your code.

Only this works fine in the dev environment. But once you put this into production using the dist file, it will not work, since the entire resource folder that you put will not be added to dist. To do this, you need to explicitly ask the game to add the / resources folder to your level. To do this, you need to go to your /build.sbt and add these lines

 import com.typesafe.sbt.packager.MappingsHelper._ mappings in Universal ++= directory(baseDirectory.value / "resources") 

Now, if you take and check your level, you can see that it has additional resources of "resources". Then it will work for the production environment.

0
source

All Articles