Play 2.2.3无法通过Play.application().resource查看文件 [英] Play 2.2.3 can not see file by Play.application().resource
问题描述
播放2.2.3. Windows 7.
Play 2.2.3. Windows 7.
public static Result menu() throws IOException {
String path = Play.application().resource("resources/menu.json").toString();
String content = Files.toString(new File(path), Charsets.UTF_8);
return ok(content).as("JSON");
}
出现错误:
... scala-2.10 \ classes \ resources \ menu.json文件名,目录 名称或卷标语法不正确
... scala-2.10\classes\resources\menu.json The filename, directory name, or volume label syntax is incorrect
检查文件系统中的路径,我可以在那里找到我的文件:
Checking that path in file-system, I'm able to find my file there:
..\target\scala-2.10\classes\resources\menu.json
我可以在那找到它.为什么不能玩?
I'm able to find it there. Why play can't?
-
更新: 我刚刚发现我无法在计算机上的C:\根文件夹中创建文件.那也许是问题.但另一方面,我没有访问根文件夹,并且广告尝试获取只读访问权限.而且我仍然对该路径上的文件具有写访问权.
UPDATE: I've just figured out I can not create files on C:\ root folder on my machine. That maybe the issue. But on other hand I'm not accessing root folder, and ad trying to get read only access. And I do have write access to that file on that path anyway.
推荐答案
实际上,您想将menu.json
文件用作静态资产,您可以将其放置在public/resources/menu.json
文件中,然后简单地读取它:
As actually you want to use your menu.json
file as a static asset you can put it i.e. into public/resources/menu.json
file and then read it with simple:
<script>
$.get('@routes.Assets.at("resources/menu.json")');
</script>
或直接根据要求:
http://localhost:9000/assets/resources/menu.json
要通过控制器执行所需的操作,您需要通过 classpath 读取InputStream(请记住,最终它会被存档到 jar 文件中!),但必须放置在conf
文件夹中,即:conf/resources/menu.json
,然后从控制器中放置:
To do what you want via controller you need to read the InputStream by classpath (remember that finally it will be archived into jar file!) but it need to be placed in conf
folder i.e.: conf/resources/menu.json
then from controller:
public static Result menuViaControllerJson() {
InputStream is = Play.application().classloader().getResourceAsStream("resources/menu.json");
return (is != null)
? ok(is)
: notFound();
}
无论如何,您将获得与普通Assets.at
完全相同的结果,因此请考虑是否值得努力.
Anyway you will get exactly the same result as for common Assets.at
, so consider if it's worth of effort.
If you want to use this file as custom config just use HOCON syntax file i.e.: conf/ses.conf
:
foo = "bar"
并在控制器中
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
....
Config cfg = ConfigFactory.parseResources(Play.application().classloader(), "ses.conf");
debug("My 'foo' is configured as: " + cfg.getString("foo"));
这篇关于Play 2.2.3无法通过Play.application().resource查看文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!