How to load the resource file in Erlang

别等时光非礼了梦想. 提交于 2019-12-08 12:44:02

问题


What is a usual way of storing and loading resource file in Erlang. I need to create a certain human-readable dictionary and load it at application initialization. For example, in Java I would put the data in a .property file, then put it somewhere in the classpath and finally load it with help of code like this:

new Properties().load(Class.getResourceAsStream("/file.properties"))

So, I have the following questions:

  • where I can (must) keep the resource file?
  • how to determine in runtime the path to the resource file
  • how to load it (for example file:consult(Filename))

回答1:


In Erlang properties are in *.config file, that usually is (but doesn't have to be) in the root directory of your project. For example:

  • Chicago Boss has boss.config
  • RabbitMQ has rabbitmq.config
  • Zotonic has different configs for different sites stored in priv/sitename/config

You can provide config file by running

erl -config myconfig

WARNING: the file should be named "myconfig.config" and you should omit the extension.

The config file should be structured this way:

[{Application1, [{Par11,Val11},...]},
 ...,
{ApplicationN, [{ParN1,ValN1},...]}].

for example:

[{kernel, [
    {my_key, "value"}
]}].

Than in erlang shell, you can type:

application:get_env(kernel, my_key).
{ok,"value"}

I used kernel application, because it is always loaded and application:get_env/2 returns undefined, if the application is not loaded. You should put any configs in your own application and make sure, that it is loaded before invoking get_env/2.

Also, configs are hierarchical, you can put the defaults in *.app file, that user usually doesn't have to modify. You can overwrite them in config file and finally, you can provide the key value pairs in command line (they will overwrite things, that are in config file).

You can read more about configuration here:

http://www.erlang.org/doc/design_principles/applications.html#id74398

You can also make config file more user friendly by using comments, example:

https://github.com/ChicagoBoss/ChicagoBoss/blob/master/skel/boss.config




回答2:


I found the answer myself. The prefered path to store resource files is a priv directory. code:priv_dir/1 returns the path to the priv directory in an application.

Here is a code snippet to load JSON from the file:

File = filename:join([code:priv_dir(application), "resource.json"]),
{ok, Text} = file:read_file(File),
%% parse json


来源:https://stackoverflow.com/questions/25413887/how-to-load-the-resource-file-in-erlang

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