How to read a file in Play Framework 2.2.1?

两盒软妹~` 提交于 2020-01-03 11:02:53

问题


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.


回答1:


You can place any resource file in the folder /conf and load it (Programatically) as explained here: Custom configuration files - Play! Framework 2.0




回答2:


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



回答3:


I have answered to a similar question at https://stackoverflow.com/a/37180103/5715934. I think the same answer will be applied for you too.

You can choose a location you prefer other than in dedicated folders for some specific tasks. For an example you can create /resources folder. Don't make any resource folder inside /app folder since it is only a location to store code. Same goes 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 will work perfectly on dev environment. But once you put this in production using the dist file it will not work since the entire resources folder you put will not be added to the dist. In order to do that, you have to explicitly ask play to add the /resources folder to your dist also. For that what you have to do is 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 dist, you can see it has an additional folder 'resources' inside the dist. Then it will work for the production environment also.



来源:https://stackoverflow.com/questions/21918786/how-to-read-a-file-in-play-framework-2-2-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!